0

I'm working on code for school and ran into a problem while reading user input. I made a new class for testing to see if it is my code around it and it's not. Here is the simplified code.

    import java.util.*;
public class practice {
    public static void main(String[] args){
      Scanner kb = new Scanner(System.in) ;
      String fullname = kb.nextLine();
      int age = kb.nextInt();
      String program = kb.nextLine();
    * int number = kb.nextInt();
      System.out.println(fullname);
      System.out.println(age);
      System.out.println(program);
      System.out.println(number);
    }
}

The following error comes up

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 practice.main(practice.java:8)

I've marked where the error is incurring. Why is this happening and how can I fix this?

What I've tried so far: - Added kb.nextLine() after the first kb.nextLine() - Tried to reset the scanner after each input

1 Answers1

0
  Scanner kb = new Scanner(System.in) ;
  String fullname = kb.nextLine();
  int age = kb.nextInt();
  kb.nextLine();
  String program = kb.nextLine();
  int number = kb.nextInt();

  kb.nextLine();
  System.out.println(fullname);
  System.out.println(age);
  System.out.println(program);
  System.out.println(number);

Ref: InputMismatchException when using Sacnner nextLine for String

RRIL97
  • 852
  • 2
  • 9
  • "works fine" ok, but why does it work? What is the significant change? A good answer spells it out, rather than just dumping code and saying "this will work". – Andy Turner Mar 15 '20 at 20:29
  • 1
    You are right hence I have added reference. Pretty good explanation there. – RRIL97 Mar 15 '20 at 20:31