1

I was implementing a simple HashMap program which stores name and age of persons. here is my code:

import java.util.*;

class StoreName {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 5; i++) {
            String name = sc.nextLine();
            int age = sc.nextInt();
            map.put(name, age);
        }

        for (String key : map.keySet())
            System.out.println(key + "=" + map.get(key));
    }
}

when I take input from nextInt() the Scanner throws InputMismatchException Exception but if I take input from nextLine() and then parse it into int then my code runs properly.Please explain me.

and why should I use nextInt() or nextDouble() anyway if I could parse string input into any type.

almightyGOSU
  • 3,698
  • 6
  • 27
  • 39
prak
  • 113
  • 1
  • 8
  • possible duplicate of [Scanner issue when using nextLine after nextXXX](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx) – Tom Jun 28 '15 at 10:32

2 Answers2

6

sc.nextInt() doesn't read the entire line.

Suppose you enter

John
20
Dan
24

Now let's see what each Scanner call will return :

  String name=sc.nextLine(); // "John"
  int age=sc.nextInt(); // 20
  String name=sc.nextLine(); // "" (the end of the second line)
  int age=sc.nextInt(); // "Dan" - oops, this is not a number - InputMismatchException 

The following small change will get over that exception :

for(int i=0;i<5;i++)
{
   String name=sc.nextLine();
   int age=sc.nextInt();
   sc.nextLine(); // add this
   map.put(name,age);
}

Now, Scanner will behave properly :

String name=sc.nextLine(); // "John"
int age=sc.nextInt(); // 20
sc.nextLine(); // "" (the end of the second line)
String name=sc.nextLine(); // "Dan"
int age=sc.nextInt(); // 24
sc.nextLine(); // "" (the end of the fourth line)
Eran
  • 359,724
  • 45
  • 626
  • 694
  • I have one more question.Is there any specific benefit of using nextInt() over parsing the string input into integer type?Please explain. – prak Jun 28 '15 at 12:39
  • @prak I don't see any benefit in using nextInt. Internally it is calling `Integer.parseInt` and throws InputMismatchException when it catches a NumberFormatException. I prefer to do parse the String inputs myself. – Eran Jun 28 '15 at 12:44
1

Try using sc.next() for reading name instead of using nextLine()

for (int i = 0; i < 5; i++) {
    String name = sc.next();//Change here
    int age = sc.nextInt();
    map.put(name, age);
}

A detailed explanation on the difference between next() and nextLine() can be found here

What's the difference between next() and nextLine() methods from Scanner class?

Community
  • 1
  • 1
bane19
  • 374
  • 2
  • 13