0

I am very new to java. But i have been given a requirement to map student with their respective id, as key value pair.

When the user enters the required id, the system would print the student name associated with it. if no name is found associated with id(no value with key), it would print the student is not available.

****The program is not working when i am using sc.nextLine instead of sc.next in the same code to read the string line for student name input and an arrayoutofbound exception is generated. ****

Example of the flow:

Enter the number of student:
4(say)
Enter the id of the student:
11
12
13
14
Enter the number of the student name:
4(say)
Enter the name of the students:
Tom
Harry
Jim
Jerry
Enter a student id:
14(say)
The output would be:
the key is 11 and value is Tom
the key is 12 and value is Harry
the key is 13 and value is Jim
the key is 14 and value is Jerry
the value of the id 14 is jerry

.Can you please help me out in this?

Program:

public class HashMapDemo {
    public static void main(String args[]){

        // fill the code
        int a,i=0,c,e;
        Scanner sc = new Scanner(System.in);
        HashMap<Integer, String> hmap = new HashMap<Integer, String>();
        System.out.println("Enter the number of student");
        a = sc.nextInt();
        System.out.println("Enter the student id");
        int[] b = new int[a]; 
        for (i=0;(i<b.length);){

            b[i] = sc.nextInt();
            i++;
            }

        System.out.println("Enter the number of student name available");
        c = sc.nextInt();
        System.out.println("Enter the student name");
        String[] d = new String[c];
        for (i=0;i<d.length;i++){

      //if i am using sc.nextLine instead of sc.next araayoutofbound //exception is generated

        d[i] = sc.next();

        }

        System.out.println("Enter the student id");
        e = sc.nextInt();
for (i=0;i<c;i++)
        {
        hmap.put(b[i], d[i]);
        }
        System.out.println("The values are:"+hmap);
      Set set = hmap.entrySet();
      Iterator it = set.iterator();
      while(it.hasNext()){
          Map.Entry me = (Map.Entry)it.next();
          System.out.println("key is:"+me.getKey()+" & value is: "+me.getValue());
      }
      String var = hmap.get(e);
      System.out.println("The value of id is:"+var);

                   }
               }
luciferxxx
  • 59
  • 1
  • 8
  • please explain it more clear, you've sent all the code – Mohsen_Fatemi Dec 15 '17 at 10:51
  • Please work really hard in limiting down your question to the bare minimum. – Micha Wiedenmann Dec 15 '17 at 10:54
  • I have tried to edit it to make it more clear. Please let me know if anything is missed. Sorry for the inconvinience caused.Thanks – luciferxxx Dec 15 '17 at 11:13
  • Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – AxelH Dec 15 '17 at 11:24
  • You have a problem when you call `nextLine` probably because before the loop, you call `nextInt`, see the duplicate to understand why this could be a problem. This doesn't not answer your problem directly, but this is most likely linked. Please provide a [mcve] if you want a more specific answer. – AxelH Dec 15 '17 at 11:24
  • Hi AlexH..thanks..i will check for your suggestions as mentioned above and try to provide the best suitable example.. – luciferxxx Dec 15 '17 at 11:40

2 Answers2

0

Since you are consuming int with your Scanner using nextInt, the buffer keep every \n in it, so if you need to use nextLine after any next### from the Scanner class, you need to first read that remaining character simply using nextLine. For the moment, if you provide 2 names, the first one will be skipped like the following test shows it

Enter the number of student
3
Enter the student id
1
2
3
Enter the number of student name available
2
Enter the student name
Foo
Enter the student id
1
The values are:{1=, 2=Foo}
key is:1 & value is: 
key is:2 & value is: Foo
The value of id is:

The first key doesn't have a name, the first nextLine call take the remaining content in the Scanner, leaving an empty String

But if you consume the buffer correctly with nextLine after a nextInt (only necessary if you want to read the full line), this will not be the case anymore :

c = sc.nextInt();
sc.nextLine(); //read the remaining content let by the previous `nextInt`

System.out.println("Enter the student name");
String[] d = new String[c];
for (i=0;i<d.length;i++){
    d[i] = sc.nextLine();
}

For more information, simply check Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?

Some improvement using the correct types with the Set, you don't need to cast anything like this

Set<Entry<Integer,String>> set = hmap.entrySet();
Iterator<Entry<Integer,String>> it = set.iterator();
while(it.hasNext()){
    Entry<Integer, String> me = it.next();
    System.out.println("key is:"+me.getKey()+" & value is: "+me.getValue());
}
AxelH
  • 13,322
  • 2
  • 21
  • 50
  • Hi Alex..I got the point where we need to consume the buffer and it is working fine now. i am now trying to print a message if a student id is found which is not mapped to any student name(Key not mapped to any value) – luciferxxx Dec 15 '17 at 11:50
  • @luciferxxx just take your time to work that problem, if you can't find a working solution, post another question, those are too distinct, but you should try to reduce the code of the question next time providing a [mcve]. Just a hint and I let you try by yourself, see [`Map.values`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#values--) to or simply iterate like you did and check the `Entry.getValue()` result to get the `id`. PS: check the edit to see how you could improve the code with the correct types. – AxelH Dec 15 '17 at 11:58
  • Hi AxelH..Thanks for your suggestions. The code is working absolutely fine now and covering all the scenarios. – luciferxxx Dec 15 '17 at 12:00
  • Have fun learning JAVA @luciferxxx, this is not always simple but this worth it ;) – AxelH Dec 15 '17 at 12:01
-1
public class StudentMap {

    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        System.out.println("Enter num of students");
        int size=scan.nextInt();
        Map<Integer, String> students=new HashMap<>();
        for (int i = 0; i < size; i++) {
            System.out.println("Enter id");
            Integer id=scan1.nextInt();
            System.out.println("Enter name");
            scan=new Scanner(System.in);
            String name=scan1.nextLine();
            students.put(id, name);
        }
        for (Map.Entry<Integer, String> student: students.entrySet()) {
            System.out.println("Student id= "+student.getKey()+" Student name= "+student.getValue());
        }
    }
}

Check this code. It will give you students map with key value pair.

Shailesh Jain
  • 33
  • 1
  • 6
  • Hi Sailesh..the code is asking for id and name one after another. I am trying to get all id;s at once and the all name at once.Then the user enters the required id. This is where error is getting generated while using sc.nextLine. Thanks – luciferxxx Dec 15 '17 at 11:19
  • Just add sc1 = new Scanner(System.in); sc1.nextLine(); inside for loop. – Shailesh Jain Dec 15 '17 at 11:24
  • Why do you instantiate another `Scanner` on the same `InputStream` ? – AxelH Dec 15 '17 at 11:25
  • It's always skipping nextLine() because instance sc already have used with nextInt() and all. – Shailesh Jain Dec 15 '17 at 11:28
  • I have tried in my code also. If once `nextInt()` used with one instance it's skipping `nextLine()` inside for loop. – Shailesh Jain Dec 15 '17 at 11:34
  • Of course, this is well know behavior. But you are instantiating a new `Scanner` on each iteration for nothing ... this is not the solution, mainly because a `Scanner` should always be close when you are done with it ... but you can't closed those `scan1`. Just consume the next token in the buffer. – AxelH Dec 15 '17 at 11:36
  • Just see my edited code. I am finding that one way only. If can help on this. – Shailesh Jain Dec 15 '17 at 11:41
  • Just check my answer to understand why you don't need to declare a `Scanner` again and again. This is a classic mistake but easy to remember once you understand what the `next###` methods do. – AxelH Dec 15 '17 at 11:48