简体   繁体   中英

Scanner input validation in while loop

I've got to show Scanner inputs in a while loop: the user has to insert inputs until he writes "quit". So, I've got to validate each input to check if he writes "quit". How can I do that?

while (!scanner.nextLine().equals("quit")) {
    System.out.println("Insert question code:");
    String question = scanner.nextLine();
    System.out.println("Insert answer code:");
    String answer = scanner.nextLine();

    service.storeResults(question, answer); // This stores given inputs on db
}

This doesn't work. How can I validate each user input?

The problem is that nextLine() "Advances this scanner past the current line". So when you call nextLine() in the while condition, and don't save the return value, you've lost that line of the user's input. The call to nextLine() on line 3 returns a different line.

You can try something like this

    Scanner scanner=new Scanner(System.in);
    while (true) {
        System.out.println("Insert question code:");
        String question = scanner.nextLine();
        if(question.equals("quit")){
            break;
        }
        System.out.println("Insert answer code:");
        String answer = scanner.nextLine();
        if(answer.equals("quit")){
            break;
        }
        service.storeResults(question, answer);
    }

Try:

while (scanner.hasNextLine()) {
    System.out.println("Insert question code:");
    String question = scanner.nextLine();
    if(question.equals("quit")){
     break;
    }

    System.out.println("Insert answer code:");
    String answer = scanner.nextLine();

    service.storeResults(question, answer); // This stores given inputs on db
}

always check if scanner.nextLine is not "quit"

while (!scanner.nextLine().equals("quit")) {
    System.out.println("Insert question code:");
    String question = scanner.nextLine();
    if(question.equals("quit"))
     break;

    System.out.println("Insert answer code:");
    String answer = scanner.nextLine();
    if(answer.equals("quit"))
      break;

    service.storeResults(question, answer); // This stores given inputs on db 

}

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