1

I have the following code used in my program:

do {
    if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) {
        addItems(numOfItems);

    } else {
        System.out.println("That number is out of range.");
        System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
        numOfItems = scan.nextInt();
    }
} while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);

which, when run, keeps repeating the method which I only want to happen once. How to I make the loop keep repeating for validation, but only run the method once?

2 Answers 2

3

Replace

while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);

with

while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);

Update

From your comment to the answer, it looks like you need to do something like following:

do {
    numOfItems = scan.nextInt();
    if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) {
        addItems(numOfItems);

    } else {
        System.out.println("That number is out of range.");
        System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");

    }
} while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);

However, you can optimize this to something like following:

while ((numOfItems = scan.nextInt() != 3) && numOfItems != 5 && numOfItems != 7 && numOfItems != 9) {

            System.out.println("That number is out of range.");
            System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
}

addItems(numOfItems);
Sign up to request clarification or add additional context in comments.

5 Comments

That fixes the solution, however, now it doesn't validate correctly. If I enter in a number not 3, 5, 7, or 9 then enter one of those numbers, the method doesn't run?
Isn't that a desirable behavior? Keep on running the loop until the user enters one of those 4 numbers? If this is not the desired behavior, you need to provide more explanation
@Kooba: What do you mean by "the method." The code excerpt you provided does not call any method.
@VHS Your first solution fixed my problem. Not sure how exactly but it works optimally now, thanks!
@Kooba, glad that I could be of help.
1

You might want to correct

while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);

since, it would always be true.

You can get rid of this(do..while) condition if you always want to execute the do{...} block of statements. ("...which I only want to happen once")

Comments

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.