ALx ALx ALx ALx - 7 months ago 12
Java Question

Java. Multiple while conditions and boolean

I am trying to do a school project and I'm having problems; my code is:

public class Class {
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
int code = 0, i = 0;
boolean error = true;
//Start of program
System.out.println("Inputs ------------------");
//Ask for input
do {
System.out.print("Code: ");
code = lector.nextInt();
if ( code < 0 || code > 2000) {
error = false;
} i = i + 1;
} while (!error || i < 3);

if (error) {...rest of the program


My problem is that I need to exit the loop if the input is > 0 & < 2000, and I need to stop executing the program if the user exceed 3 intents.

Any help would be very apreciated! Thank you!

Answer

This

while (!error || i < 3);

should be

while (!error && i < 3);

You want to continue looping while error is false and i < 3. Also i = i + 1; can be written as i++ (or with a preincrement). So you could do

boolean valid = false;
do {
    System.out.print("Code: ");
    code = lector.nextInt();
    if (code > 0 && code < 2000) {
        valid = true;
    }
    i++;
} while (!valid && i < 3);