【发布时间】:2018-02-04 23:16:52
【问题描述】:
我有一个程序,它假设询问用户什么 txt 文件,浏览 txt 文件并找到所有可解析的整数并将它们平均。我在下面有以下代码,但它给了我一堆错误。所有这些错误的原因是什么?
txt文件为: 5 15 312 16 八七 44 八万五千六十二 13 98 93
import java.util.Scanner;
public class Ch12Pt2 {
public static void main(String[] args) throws NumberFormatException {
Scanner input = new Scanner(System.in);
System.out.print("Enter filename: ");
String filename = input.nextLine();
Scanner file = new Scanner(filename);
if(file.nextLine().equals(""))
{
System.err.println("Could not find file:" + filename);
System.exit(1);
}
do {
try {
int total = 0;
int count = 0;
int num = file.nextInt();
total = num + total;
//Display the results
System.out.println("The number of parsable numbers: " + count);
System.out.println("Average values: " + (total / count));
}
catch (NumberFormatException ex) {
System.out.println("Cannot parse " + num + " as an integer.");
file.nextInt();
}
} while (file.hasNextInt());
// Close the files
input.close();
file.close();
}
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Ch12Pt2.main(Ch12Pt2.java:21)
【问题讨论】:
-
eight不是int,因此file.nextInt()将失败 -
@MadProgrammer 我认为 NumberFormatException 会控制它。
-
java.util.NoSuchElementException不继承自NumberFormatException或任何共同祖先,所以我不会抓住它 -
另外,
Scanner file = new Scanner(filename);不正确,这是将Stringfilename传递给要处理的Scanner,相反,您可能是指Scanner file = new Scanner(new File(filename));,它实际上会读取指定的文件