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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With