Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep Looping until inputs are available in java

Tags:

java

c++

loops

If I don't know the input size already, what is the the way to keep iterating in a loop until it is available, in JAVA. In C++ it can be done as following.

int main(){
    int val;
    while(cin >> val){
           //do stuff
    } 
}

What is the way to do similar thing(as above) in java

Thanks in Advance. Shantanu

like image 266
shantanu Avatar asked May 29 '26 23:05

shantanu


2 Answers

You should try the following thing.

    long val;
    Scanner sc = new Scanner(System.in).useDelimiter("\n");
    while (sc.hasNext()) {
        String temp = sc.next().trim();

        val = Long.parseLong(temp);
        // do stuff
    }

One way is to use Scanner.

long val;
Scanner sc=new Scanner(System.in);
while (sc.hasNextLong() ) {
    val = sc.nextLong();
    // do stuff
}

This is equivalent to the cpp code you provided. But not exactly what you asked for. It will loop as long as there are legal inputs in the read string.

like image 28
example Avatar answered May 31 '26 14:05

example