为什么hasNextLine()永远不会结束?

Hel*_*lgi 13 java java.util.scanner

对不起,如果听起来太简单了.我是Java的新手.

这是我用来检查的一些简单代码hasNextLine().当我运行它时,我无法阻止它.我想如果你没有写任何输入并按下Enter,你就会逃脱while循环.

有人可以向我解释hasNextLine()在这种情况下如何运作?

import java.util.*;

public class StringRaw {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String str = sc.nextLine();
        }
        System.out.print("YOU'VE GOT THROUGH");
    }
}
Run Code Online (Sandbox Code Playgroud)

Law*_*Dol 16

从System.in读取时,默认情况下,您正在从键盘读取,这是一个无限输入流...它具有用户关心键入的行数.我认为发送EOF的控制序列可能有效,例如CTL-Z(或CTL-D?).

看看我好的'ASCII图表...... CTL-C是ETX,CTL-D是EOT; 其中任何一个都应该用于终止文本流.CTL-Z是一个不应该工作的SUB (但它可能,因为控制在历史上是高度主观地解释的).


use*_*own 5

Ctrl+ D键终止stdin的输入.(Windows:Ctrl+ Z)或从命令提供输入:

echo -e "abc\ndef" | java Program
Run Code Online (Sandbox Code Playgroud)


Jim*_*Jim 5

CTRL-D是UNIX / Linux的字符或字节流的结尾,而CTRL-Z是Windows的字符或字节流的结尾(Microsoft DOS最早的历史产物)。

编写问题代码后,空行将不会退出循环,因为hasNextLine()不会求值为false。在输入字节流中将有一个行终止符。

System.in是来自标准输入(通常是控制台)的字节流。因此,结束字节流将停止循环。尽管nextLine()不会阻止等待输入,但是hasNextLine()会阻止。按照设计,代码终止的唯一方法是在Windows中使用CTRL-Z或在UNIX / Linux中使用CTRL-D终止字节流,这导致hasNextLine()不会阻塞等待输入并返回布尔值false,从而终止while循环。

如果希望它以空行终止,则可以作为循环继续条件的一部分检查非空行。以下代码演示了如何将使用hasNextLine()和nextLine()的基本问题设计更改为在出现空行或输入字符结尾时终止的问题(即Windows中为CTRL-Z或UNIX /中为CTRL-D Linux)。while条件中的附加代码使用了赋值运算符的功能,其中它们可以像表达式一样进行求值,以返回已赋值的值。由于它是一个String对象,因此String.equals()方法可以与评估一起使用。

其他附加代码仅添加了一些打印输出,以使正在发生的事情显而易见。

// HasNextLineEndDemo.java
import java.util.*;

public class HasNextLineEndDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // this code is a bit gee-whiz
        // the assignment expression gets assigned sc.nextLine()
        // only if there is one because of the &&
        // if hasNextLine() is false, everything after the &&
        // gets ignored
        // in addition, the assignment operator itself, if
        // executed, returns, just like a method return,
        // whatever was assigned to str which, 
        // as a String object, can be tested to see if it is empty
        // using the String.equals() method
        int i = 1; // input line counter
        String str = " "; // have to seed this to other than ""
        System.out.printf("Input line %d: ", i); // prompt user
        while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
            System.out.printf("Line %d: ", i);
            System.out.println("'" + str + "'");
            System.out.printf("Input line %d: ", ++i);
        } // end while
        System.out.println("\nYOU'VE GOT THROUGH");
    } // end main
} // end class HasNextLineEndDemo
Run Code Online (Sandbox Code Playgroud)