Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide loop conditions that are not Boolean

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.

like image 980
agentK Avatar asked Feb 19 '26 17:02

agentK


2 Answers

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.

like image 74
GhostCat Avatar answered Feb 22 '26 06:02

GhostCat


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

like image 42
charles-allen Avatar answered Feb 22 '26 07:02

charles-allen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!