我有一个txt,我想扫描它,每次我读取一个整数,我想将它输入到我已经创建的数组中。
每当它读取除int之外的其他内容时,如何抛出异常,例如String,double或甚至是空行?
这是我读取文件并完成数组的方式:
file= new Scanner(new File(file_name));
int[] txt = new int[cnt]; // cnt , the number of lines in my txt
while ( file.hasNextInt()) {
txt[count] = file.nextInt();
count++;
}
谢谢 :)
将hashNextInt()
更改为hasNext()
,您将根据要求获得例外,
while (file.hasNextInt()) {
至
while (file.hasNext()) {
如果要在不抛出异常的情况下检测问题,请添加Elliott的答案:
while (file.hasNext()) {
if (file.hasNextInt()) {
txt[count] = file.nextInt();
count++;
} else {
System.error.println(file.next() + " is not an int"); // also skips bad data
}
}
(提示:阅读并尝试理解逻辑......)