我需要从Java中的随机扫描文本文件中只读整数。我不能让它跳过非整数和整个代码中断
问题是,我得到一个随机文本文件,我必须让我的代码读取它,并从范围(0-100)中获得平均值,并且不能计算非整数。我的问题是,在while循环启动并转到if语句之后,我的代码会检查文本文件中的值,如果它看到任何非整数,它就会完全停止。 我不知道如何解决这个问题。我想在if语句中可能有一些东西告诉扫描器跳过任何字符串,但我不知道如何做到这一点。 我试着做这件事。skip()方法,它让我的代码正常运行,但一旦您输入字符(a-z和大写),它就不会让代码运行。我能做些什么来解决这个问题? 输入文件示例:2323445510003958
代码:
Scanner input = new Scanner(System.in);
//asks for file's name
System.out.print("Input File's name: " );
String inputFile = input.nextLine();
//reads the files data
File file = new File(inputFile);
Scanner scanFile = new Scanner(file);
//finds average and totalCount
while(scanFile.hasNext()) {
String pattern = "[a-zA-Z]*";
scanFile.skip(pattern);
num = scanFile.nextInt();
if(num >= 0 && num <= 100) {
sum += num;
totalCount++;
average = sum/totalCount;
if(num >= 90) {
gradeACount++;
percentage = (gradeACount / (float)totalCount) * 100;
}
if(num < minimumScore)
minimumScore = num;
if(num > maximumScore)
maximumScore = num;
}
}
scanFile.close();
# 1 楼答案
此任务不需要使用
skip()
。 您可以检查下一个标记是否为整数,并跳过所有非整数。 例如:输出: