java - 如何使 StdIn.isEmpty() 返回 true?

标签 java eclipse algorithm stdin

我正在使用 Algorithms Coursera 算法类(class)中提供的 Princeton 库中的 StdIn.isEmpty() 方法,但对它的工作原理感到困惑。我有声明

while (!StdIn.isEmpty())

包含一些读取用户输入的代码,但我似乎无法跳出循环。根据我的理解,如果我在没有输入任何文本的情况下按回车键,这应该意味着标准输入为空并且 while 循环应该被打破。我查找了 isEmpty 的代码,但没有说明任何问题:

public static boolean isEmpty() {
    return !scanner.hasNext();
}

谁能解释一下标准输入的工作原理并帮助我纠正对这种方法的误解?

最佳答案

Before reading each number, the program uses the method StdIn.isEmpty() to check whether there are any more numbers in the input stream. How do we signal that we have no more data to type? By convention, we type a special sequence of characters known as the end-of-file sequence. Unfortunately, the terminal applications that we typically encounter on modern operating systems use different conventions for this critically important sequence. In this book, we use Ctrl-D... Computer Science Sedgewick

因此 isEmpty 实际上是 isCtrl-D

此外,在终端应用程序中尝试 StdIn.isEmpty() 之前没有任何东西将使您没有 boolean 值,而是标准输入流请求输入。所以当像下面这样的程序运行时:

public class Average
  {
     public static void main(String[] args)
     {  // Average the numbers on standard input.
        double sum = 0.0;
        int n = 0;
        while (!StdIn.isEmpty())
        {  // Read a number from standard input and add to sum.
           double value = StdIn.readDouble();
           sum += value;
           n++;
        }
        double average = sum / n;
        StdOut.println("Average is " + average);
     }
 } 

,第一次决定条件while (!StdIn.isEmpty)时弹出标准输入流,而不是StdIn.readDouble()。如果您随后输入一些数字,返回它们,导致标准输入流非空,程序将跳转到 while 体内。我通过测试发现是这样的

> java Average
 [DrJava Input Box] (And I hit Ctrl+D here)
Average is NaN

NaN 表示 n = 0,这意味着 while 主体未被触及。

关于java - 如何使 StdIn.isEmpty() 返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401347/

相关文章:

java - 如何通过 ssl 从 wsdl 生成 jax ws 工件

算法的算法分析(big-O)

java - Eclipse 和未经检查的转换警告不应该出现

android - Ant + Proguard 提供 android-support-v4.jar 错误

c++ - 二分匹配

algorithm - 如何计算对数系列的平方和

java - Struts 2 Eclipse 类未找到错误

java - 从 PRAGMA table_info() 获取名称和类型

java - 如何测试 hibernate 通用 dao 模式

java - 下一个/上一个编辑位置 Eclipse 快捷方式 - 和 Netbeans?