0

I am trying to add space separated inputs to hashmap using for loop but I got some problems

    int G = s.nextInt();
    for (int i = 0; i < G; i++) {
        System.out.println("List girls qualities");     
        int j=1;
        String gir=s.next();
        String[] numbers = gir.split(" ");
        girlQualities=new HashMap<>();
        for (int x=0;x<numbers.length;x++)  
        {  
            int z=Integer.parseInt(numbers[x]);
            girlQualities.put(j,z); 
            j++;
        }
    }

When I used nextLine() its showing NumberFormatException but even now its not working. Please help me My target is to add numbers in this way

    3 
1 2 5 6 
1 2 3 4 5 
1 2 3 4 
Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
Rognik
  • 145
  • 9

1 Answers1

1

Thats because the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine

Try

        int G = s.nextInt();
        s= new Scanner(System.in);

And then try nextLine() Method

Refer the Link

Community
  • 1
  • 1
gifpif
  • 4,087
  • 3
  • 28
  • 44
  • kindly could you please explain why its happening. nextLine should return current line. I am little bit confused about the above scenario – Rognik Apr 12 '17 at 10:43
  • Click the Refer link given at the end of answer for detailed expiation .. – gifpif Apr 12 '17 at 10:45