【问题标题】:Why gets my code after end of file statement ignored?为什么在文件语句结束后忽略我的代码?
【发布时间】:2020-09-30 16:22:52
【问题描述】:

我目前正在尝试学习 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 语句不起作用?

【问题讨论】:

  • 对我来说似乎没问题。
  • Windows 也使用 control-d 表示 eof。
  • 这对我来说很好。我使用的是 Windows 和 BlueJ。我使用 control-d 退出。
  • 我相信linux上的control-z是用来把当前进程放到后台的。

标签: java eof


【解决方案1】:

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

显然,在您的系统上,这不起作用。如果您在 IDE 的“控制台”中运行它,它们通常不会让您关闭 sysin 或以不同于命令行的方式工作。

您可以尝试找出哪个巫毒键组合结束了事情,但还有另一种选择。

代替EOF,或者除了EOF之外,制作另一个结束输入的符号。也许0,或“结束”。在后面的情况下你不能再依赖nextInt,你必须调用next,检查它是否是END,如果是,则停止接受输入,如果不是,将它通过Integer.parseInt扔到以数值结尾。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2018-09-07
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多