简体   繁体   中英

How to run scanner in a while loop

    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

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

}

You can Use the do-while loop also

`do{

//your code here

}while(condition)`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM