为什么忽略文件结尾语句后的代码



我目前正在尝试课本上关于学习java的一个例子,但我在EoF语句后的代码被编译器忽略了。

package lettergrades;
import java.util.Scanner;
public class LetterGrades {

public static void main(String[] args) {
int total = 0;
int gradeCounter = 0;
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;

Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n", "Enter the integer grades in the range 0-100", "Type the end-of-file indicator to terminate input", "on unix type <ctrl> d then press Enter","On windows type <Ctrl> z then press enter");
while (input.hasNext()){
int grade = input.nextInt();
total += grade;
++gradeCounter;
switch (grade/10){
case 9:
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case 7: 
++cCount;
break;
case 6:
++dCount;
break;
default: 
++fCount;
break;
}
}
System.out.printf("%nGrade Report:%n");
if (gradeCounter !=0){
double average = (double) total/gradeCounter;
System.out.printf("total of the %d grades entered is %d%n", gradeCounter, total);
System.out.printf("Class average is %.2f%n", average);
System.out.printf("%n%s%n%s%d%n%s%d%n%s%d%n%s%d%n%s%d%n", "Number of students that received each grade","A: ", aCount, "B: ", bCount , "C: ", cCount, "D: ", dCount, "F: ", fCount);

}
else 
System.out.println("No grades were entered");

}
}

这是我得到的输出:

Enter the integer grades in the range 0-100
Type the end-of-file indicator to terminate input
on unix type <ctrl> d then press Enter
On windows type <Ctrl> z then press enter

但当我输入ctrl D并按下回车键时,什么也没发生。为什么printf和if语句不起作用?

例如@FredLarson正在报告,它对大多数人来说都很好。您所依赖的EOF字符导致sysin被关闭,这反过来又会导致扫描仪的hasNext()返回false。

显然,在你的系统中,这是不起作用的。如果你在IDE的"控制台"中运行这个,它们通常不允许你关闭sysin或以不同于命令行的方式工作。

你可以试着弄清楚哪种巫毒键组合会结束事情,但也有其他选择。

代替EOF,或者除了EOF之外,制作另一个结束输入的符号。可能是0或"END"。在以后的情况下,您不能再依赖nextInt,您必须调用next,检查它是否为END,如果是,停止接受输入,如果不是,则通过Integer.parseInt将其抛出以获得一个数值。

现在,您不再需要在控制台消息中提及各种平台,并且可以避免这些问题。

最新更新