Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Kurt Bourbaki Avatar asked Nov 13 '13 10:11

Kurt Bourbaki


1 Answers

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
}
like image 179
user2986555 Avatar answered Sep 19 '22 12:09

user2986555