I am currently writing a program to which sets the dynamic hashmap limit and ask user to enter key , values and then read the hashmap..
below is my code: where I have create 3 sepeate methods to read data from hashmap
package ToRemoventhHashmap;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import codingInerviewQuestions.programToRemoveTheDuplicate;
public class nthElementRemoval {
String readInput,dataInput1,dataInput2;
Integer limitValue;
public Integer specifyHashmapLimit() {
Scanner dataInput1 = new Scanner(System.in);
System.out.println("Enter hashmap limit");
limitValue = dataInput1.nextInt();
dataInput1.close();
return limitValue;
}
public HashMap<Integer,String> dataInputHashmap() {
HashMap<Integer,String> hmap = new HashMap<Integer,String>();
Scanner dataInput2 = new Scanner(System.in);
System.out.println("Enter key Values in Hashmap");
for (int i = 0; i < limitValue; i++) {
Integer a = dataInput2.nextInt();
String b = dataInput2.next();
hmap.put(a, b);
}
// limitValue = dataInput2.nextLine();
dataInput2.close();
return hmap;
}
public void readHashmapData() {
System.out.println("Hashmap key valuues are:");
for (Map.Entry<Integer, String> m : dataInputHashmap().entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nthElementRemoval nthRem = new nthElementRemoval();
System.out.println("hashmap limit specided is"+ nthRem.specifyHashmapLimit());
nthRem.dataInputHashmap();
nthRem.readHashmapData();
}
}
After running this I am getting below error:
Enter hashmap limit
2
hashmap limit specided is2
Exception in thread "main" Enter key Values in Hashmap
java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at JavaT/ToRemoventhHashmap.nthElementRemoval.dataInputHashmap(nthElementRemoval.java:25)
at JavaT/ToRemoventhHashmap.nthElementRemoval.main(nthElementRemoval.java:50)
Could you help me how to fix this ?