Home > Back-end >  While loops continues until specific user input is triggered
While loops continues until specific user input is triggered

Time:07-05

This program takes a String followed by an integer as input and then outputs a sentence using the inputs. The program repeats until the string "quit" is typed. It appears the problem is with the nextLine() and nextInt() but I cannot wrap my head around it. I am getting the following error:

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at LabProgram.main(LabProgram.java:8)


import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      
      String inputStr = in.nextLine();
      int inputInt = in.nextInt();
      
      while(!inputStr.equals("quit")){
       System.out.println("Eating "   inputInt   " "   inputStr   " a day keeps you happy and healthy.");
      }  
   }
}

Thanks for the help, the following code outputs successfully:

String inputStr = "";
int inputInt;

while(!inputStr.equals("quit")){
    inputStr = in.next();
    inputInt = in.nextInt();
    in.nextLine();   //this line throws an exception but
                     //program still outputs correctly

    System.out.println("Eating "   inputInt   " "   inputStr   " a day keeps you happy and healthy.");
} 
   }
} 

CodePudding user response:

You are using the scanner only in the beginning and then saving the values in variables. So you only use the values in your loop. Therefore you need to let the user enter new inputs every iteration of the loop.

Move inputStr and inputInt inside your loop:

String inputStr = "";
int inputInt;

while(!inputStr.equals("quit")){
    inputStr = in.nextLine();
    inputInt = in.nextInt();

    System.out.println("Eating "   inputInt   " "   inputStr   " a day keeps you happy and healthy.");
} 

In addiditon you have to make sure to enter the right input. The first (=String) can be anything on your keyboard. The second input must be an integer, so only numbers like 1, 2, 230, -4, .... That's where your error comes from.

CodePudding user response:

Your program only asks for input once, so inputStr never equals quit because inputStr is set once and never changes.

  • Related