I need to accept some positive integers for which I use a for loop as follows:
Scanner in = new Scanner(System.in);
for(int i=0; i<n; i++) {
num = in.nextInt();
//do something with num
}
This requires me to (a) know number of integers n beforehand (b) Use a counter i
I know Java does not accept non-Boolean expressions in loop conditions. But how can I do the same without n and i? For example, something like:
while( (num = in.nextInt()) ) {
//do something with num
}
Any type of loop (for/while/do-while) will do.
What you can do is something like:
boolean loop = true;
while (loop) {
int num = in.nextInt();
... do something with n
if (whatever) loop = false;
}
for example.
Or you use while (true) together with if (whatever) break.
In other words: you need a boolean condition, but you can control that condition within your loop body as shown above.
Loop until end of input -or- non-integer input (e.g. "exit", blank line):
while(in.hasNextInt()) {
int num = in.nextInt();
}
If you're testing in IntelliJ and want to indicate EOF explicitly: Ctrl+D or ⌘+D
If you want to read a file as your input: java MyClass < numbers.txt
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