How to take multi-line input in Java

Zaham2 :

I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)

Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.

  public static void main(String[] args) {

        ArrayList<String> in = new ArrayList<String>();
        Scanner s = new Scanner(System.in);

        while (s.hasNextLine() == true){
            in.add(s.nextLine());
            //infinite loop
        }
    }

I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.

Coronero :

You could use the empty line as a loop-breaker:

while (s.hasNextLine()){ //no need for "== true"
    String read = s.nextLine();
    if(read == null || read.isEmpty()){ //if the line is empty
        break;  //exit the loop
    }
    in.add(read);
    [...]
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328629&siteId=1