SudSwastik
SudSwastik

Reputation: 3

execution flow after while loop java

public static void main(String[] args) throws IOException {
     Scanner scan = new Scanner(System.in);
     int i=0;
     int arr[] = new int[10];
     while(scan.hasNext()){
         arr[i++] = scan.nextInt();
         System.out.println("sud");
     }
     System.out.println("hello");
}

}

If the input is 1 2 3 4 5 then it print 5 times. sud means while loop is working but it does not go to the System.out.println("hello"); line or beyond it.

Upvotes: 0

Views: 1065

Answers (2)

Mohd
Mohd

Reputation: 5613

Maybe add an if statement to check for a specific input to stop taking input(break the loop)

 while(scan.hasNext()){
     String tmp = scan.next();
     if (tmp.equals("exit"))     
         break;
     else {
     arr[i++] = Integer.parseInt(tmp);
     System.out.println("sud");
     }
 }
 System.out.println("hello");

INPUT:

1 2 3 exit

OUTPUT:

sud
sud
sud
hello

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Since you are reading the data from System.in, hasNext() waits for you to enter more data when you are running in console mode.

In order to tell Scanner that there's no more input, you need to close the input stream. On Windows, it's Ctrl+Z followed by Enter. On UNIX, it's Ctrl+D.

Your code will also work if you put the input in a file, and redirect your program to read from a file.

Note: You need to protect your code from a user entering too much data. Add i < arr.length to the loop condition, otherwise your code will stop with an exception when end-users enter 11-th number.

while(i < arr.length && scan.hasNext()) {
    ...
}

Upvotes: 1

Related Questions