0

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.

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.