1

Here i am trying to Enter and Print some details of employe and everything looks fine but i am getting an Exception why?

 import java.util.Scanner;  

    class EmpDet

        {  //here details
              int age;    
              String name;    
              int ssn;  
          public EmpDet(int age,String name,int ssn)    
        {  
           //assign to constructor

            this.age = age;    
            this. name = name;  
            this.ssn = ssn;  
            System.out.println(age+" "+name+" "+ssn); //printing details

        }  

            public static void main(String args[])  
            {  
                Scanner sc = new Scanner(System.in);  
                int age = sc.nextInt();  

                String name = sc.nextLine(); //InputMismatchException in this line
                int ssn = sc.nextInt();  
                EmpDet det = new EmpDet(age,name,ssn);  
            }
        }
harry
  • 19
  • 3
  • When you get the exception, was there any text for `sc.nextLine()` to pick up? – Tyler Feb 27 '18 at 17:12
  • are you putting dashes - in your ssn? – hellyale Feb 27 '18 at 17:14
  • @hellyale I believe the exception is occurring on the line with `sc.nextLine`, not `sc.nextInt`. – Tyler Feb 27 '18 at 17:16
  • have you tried debugging? – Cowboy Farnz Feb 27 '18 at 17:17
  • [`nextLine()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine--) **cannot** throw `InputMismatchException`. You're getting the error in the `ssn = sc.nextInt()` call, because it sees the "name", given that `nextLine()` didn't see the name (see [duplicate link](https://stackoverflow.com/q/13102045/5221149)). – Andreas Feb 27 '18 at 17:25
  • When mixing nextXxx() calls with nextLine() calls, you have to flush (discard) the end of the previous line by calling nextLine() first. – Cowboy Farnz Feb 27 '18 at 17:26

1 Answers1

1

You might want to grab line by line instead. Once you have the line, then you can try to parse the input into an Integer.

    Scanner sc = new Scanner(System.in);  
    int age = Integer.parseInt(sc.nextLine());  

    String name = sc.nextLine();
    int ssn = Integer.parseInt(sc.nextLine());  
    EmpDet det = new EmpDet(age,name,ssn);

It would be also wise to put a try catch around the parsing in case the input from the user doesn't qualify as being an Integer.

Note, nextInt() only grabs the number and not the new line (enter)

RAZ_Muh_Taz
  • 3,964
  • 1
  • 10
  • 22