1

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!

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I agree with you but then if I enter 0, I get out of the loop. And 0 shouldn't be accepted.
Then if ( code < 0 || code > 2000) { should be if ( code <= 0 || code >= 2000) { It's doing what you told it to do.
Ok, and for example if my 1st choice is number 5, how can I make it exit the loop? considering 5 is between 0 and 2000 and so the boolean is declared true.
So I need to exit the loop only if a number between 0 and 2000 is inserted and if the user exceeds 3 intents to stop the loop and the program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.