0

How would I take a simple if-else statement using a Scanner for keyboard input, compare an integer against an argument and re prompt the user to input the integer again if it is not the desired result? Here is what I have, I think this should be fairly easy but I'm only learning;

 public static void main(String[] args) {

    Scanner myInt = new Scanner(System.in);

    System.out.println("Enter a number between 1 and 10");

    int choice = myInt.nextInt();

    if (choice <= 10) {
        System.out.println("acceptable");
    } else {

                System.out.println("unacceptable");
                System.out.println("Enter a number between 1 and 10");

            }
        }
    }

Any tips on how I should approach this?

Thanks!

1
  • Try a loop. Also, don't forget that choice must be >= 1 as well. Currently you would accept 0 (or any negative value). Commented Dec 24, 2019 at 1:04

2 Answers 2

4

You could use a while loop to keep asking for numbers and checking if they are acceptable:

public static void main(String[] args) {

    Scanner myInt = new Scanner(System.in);
    boolean acceptable=false;
    while(!acceptable){
        System.out.println("Enter a number between 1 and 10");

        int choice = myInt.nextInt();

        if (choice <= 10 && choice>=1) {
            System.out.println("acceptable");
            acceptable=true;
        } else {

            System.out.println("unacceptable");

        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Not your logic though. between 1 and 10 != choice <= 10
@ScaryWombat Fixed
-1
public static void main(String[] args) {
    // TODO Auto-generated method stub

    while (true) {
        if (insertNumber()) {
            break;
        }
    }

}

public static boolean insertNumber() {

    System.out.println("Enter a number between 1 and 10");

    Scanner myInt = new Scanner(System.in);

    int choice = myInt.nextInt();

    if (choice <= 10) {
        System.out.println("acceptable");
        return true;

    } else {
        System.out.println("unacceptable");
        return false;
    }
}

1 Comment

This answer is wrong, for the same reason OP's code snippet is wrong, logically. Please be mindful before posting answers.

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.