-3

I am trying to figure out how to read input from the console in Java that would behave exactly the same as the following C++ code:

while(cin >> input)

I essentially need to keep reading the console one integer at a time, and only stop when the user enters no more integers.I am able to read integers one at a time, but cannot figure out how to get it to stop executing once the user passes an empty line. Thanks!

Joe B
  • 1
  • 1
  • 2
    There are several ways to do it with code examples: https://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in-java – Bolat Basheyev Sep 10 '20 at 20:17

2 Answers2

1
  Scanner scanner = new Scanner(System.in);

  // find the next int token and print it
  // loop for the whole scanner
  while (scanner.hasNext()) {

     // if the next is a int, print found and the int
     if (scanner.hasNextInt()) {
        System.out.println("Found :" + scanner.nextInt());
     }
     // if no int is found, print "Not Found:" and the token
     System.out.println("Not Found :" + scanner.next());
  }
0

You can use the Scanner nextLine() method and check for integers:

import java.util.*;

class TextNum {

public static void main(String[] args) {

    int n;
    String s;

     Scanner in = new Scanner(System.in);  
    while (true) {
        s = in.nextLine();
         //Do something with this
        System.out.println("This is :" + s + ":");
        try {
            n = Integer.parseInt(s);               
        } catch (Exception e) {
            break;
        }
    }
   
}

}