Home > Back-end >  How to run scanner in a while loop
How to run scanner in a while loop

Time:07-04

    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    System.out.println("1 - login");
    System.out.println("2 - regrister");

    int firstSelection = scanner.nextInt();

    while(firstSelection > 2 || firstSelection <1) {
        System.out.println(firstSelection " is not a valid entry");
        int firstSelection = scanner.nextInt();
    }
    System.out.println("you picked " firstSelection);
    }

Issue:

duplicate variable firstSelection

What I'm trying to do:

  • ask user for an input
  • When the while loop is ran. If the firstSelection is not a valid input I want to run the scanner again until they enter a valid response

What I tried:

    System.out.println("1 - login");
    System.out.println("2 - regrister");
    
    boolean fs;
    while((fs = scanner.nextInt() != 1) || (fs = scanner.nextInt() != 2)) {
        System.out.println(fs " is not a valid entry");
    }
    System.out.println("you picked " fs);

Issue:

  • if i enter 1. I get no printline saying you picked 1. If i enter it again it tells me true is not a valid entry.

  • if i enter a incorrect response it will continualy respond true is not a valid entry

CodePudding user response:

public static void main(String[] args) {
    int firstSelection;
    Scanner scanner = new Scanner(System.in);

    while (true) {
        System.out.println("1 - login");
        System.out.println("2 - regrister");
        firstSelection = scanner.nextInt();
        if (firstSelection == 1 || firstSelection == 2)
            break;
        else {
            System.out.println(firstSelection   " is not a valid entry");
            System.out.println("---------------------");
        }
    }

    System.out.println("you picked "   firstSelection);

}

CodePudding user response:

You can Use the do-while loop also

`do{

//your code here

}while(condition)`

  • Related