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.

1

2 Answers 2

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)
2
  • 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, 2015 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, 2015 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.