Scanner input validation in while loop

前端 未结 3 1492
北海茫月
北海茫月 2020-11-29 13:07

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 h

相关标签:
3条回答
  • 2020-11-29 13:41

    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 
    

    }

    0 讨论(0)
  • 2020-11-29 13:57

    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
    }
    
    0 讨论(0)
  • 2020-11-29 13:59

    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);
        }
    
    0 讨论(0)
提交回复
热议问题