Home>

I want to quit the program after entering multiple lines of data without exit conditions.

For example, when pasting multiple lines of text data prepared with Notepad etc. with copy and paste, the console will continue to wait for input after it has been read and processed.

In the case of a common problem, a numerical value indicating how many lines of data are given in the first line, so it can be terminated on the condition.

I don't know when there is no exit condition. How can I end the program after reading multiple lines of input data?

Image I want to realize (and terminate the program)

Problems i am experiencing

While (sc.hasNextLine ())thought that reading would end and exit the loop, but the next process could not be executed because the loop was not exited.

Applicable source code
import java.util.Scanner;
public class sample {
    public static void main (String [] args) {
        Scanner sc = new Scanner (System.in);
        String s = "";
        while (sc.hasNextLine ()) {
            s + = sc.nextLine ();
        }
        System.out.println (s);
    }
}
Tried

Neither of them stopped automatically.

while (sc.hasNext ()) {
while (sc.hasNextLine ()) {
Execution environment

Eclipse 4.8
Java SE 8

  • Answer # 1

    Console input only waits for input, so you need to decide the number of input lines in the code, or decide the end string and put it in, and exit it

    Many Linux tools end with Ctrl-D, Ctrl-C, or Ctrl-Z.