简体   繁体   中英

Scanner using with while loop and switch statement

I'm creating a simple console app in Java and I have a trouble. This is my code:

boolean isActive = true;
Scanner scanner = new Scanner(System.in);

do {
try {
    int option = scanner.nextInt();

    switch (option) {

        case 1:
            System.out.println("Search By Registration number: " +
                    "\n------------------------------");
            System.out.println("Enter registration number!");
            String regNumber = scanner.nextLine();
            if (regNumber == incorrect) {
                continue; // return to case 1 and ask enter regnumber one more time
            } else {
                // do stuff
            }

            break;

        case 2:
            System.out.println("Exit the search option: ");
            isActive = false;
            break;

        default:
            System.out.println("Your selection was wrong. Try one more time!");
            break;

    }
} catch (InputMismatchException ex) {
    System.out.println("Your selection was wrong. Try one more time!");
}
scanner.nextLine();
} while (isActive);

And I can't to return to case 1 if an error occured. So, if error occured, the user must get the message About entering the registration number one more time and so on.

You need to use equals() when you check a regNumber

if (regNumber.equals(incorrect)) {
      System.out.println("Incorrect!");
      continue; 
} else {
      System.out.println("Correct!");
}

But even then, your program doesn't work properly, change String regNumber = scanner.nextLine() on this:

String regNumber = scanner.next();

You could put a loop around your input for the regNumber, in order to listen for input while it's not correct.

String regNumber = incorrect;
// String is a reference type, therefore equality with another String's value
// must be checked with the equals() method

while(regNumber.equals(incorrect)){

    if (regNumber.equals(correct)) {
        // Do something if input is correct
    }

}

This may be not the exact solution you wanted, but think of the same concept and apply it to your program. Also see this for more information about String comparison. Hope this helped!

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