shoGUN
shoGUN

Reputation: 41

Java scanner and if-else statements

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!

Upvotes: 0

Views: 509

Answers (2)

jihwanlee
jihwanlee

Reputation: 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;
    }
}

Upvotes: -1

Nosrep
Nosrep

Reputation: 531

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");

        }
    }
}

Upvotes: 4

Related Questions