10

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?

4

3 回答 3

11

问题是nextLine() “使扫描仪超过当前行”。nextLine()因此,当您调用while条件并且不保存返回值时,您已经丢失了用户输入的那一行。对第 3 行的调用nextLine()返回不同的行。

你可以试试这样的

    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);
    }
于 2013-11-13T10:04:25.720 回答
4

尝试:

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
}
于 2013-11-13T10:09:09.423 回答
0

始终检查scanner.nextLine是否没有“退出”

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 

}

于 2013-11-13T10:06:43.340 回答