Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm very new to Java and could use some help here. Problem with my scanner and inputs

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.");
      }  
   }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading