Keep looping until inputs are available in java

If I don’t already know the size of the input, what will be the way to continue the loop in the loop until it is available in JAVA. In C ++, this can be done as follows.

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

How to do a similar thing (as above) in java

Thanks at Advance. Shantanu

+3
source share
5 answers

You should try the following.

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

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

One way is to use a 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 quite what you requested. It will loop until there are legal entries in the read line.

+1
source

Scanner. . , .

public static void main(String[] args)
{
    String str=new Scanner(System.in).nextLine();
}
0

Do not run busy cycles. You probably prefer to use streams. The read()stream method is blocked until the data arrives, so your code will be simple without busy cycles and will work exactly the way you want:

while ( in.read() != -1) {
   // do your stuff
}

or even better to use buffers:

byte[] buf = new buf[MAX_SIZE]
while ( in.read(buf) != -1) {
   // do your stuff
}
0
source

I believe that the best way to serve your purpose is multithreading, when one thread will wait for input from the user and let the other thread know when it will receive it. At the same time, another thread will continue to iterate through the loop.

0
source

All Articles