Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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

>Solution :

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

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading