My code is giving this error:
Index out of bounds
Why is causing this error?
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
System.out.println("First input number of your years then name:");
Scanner sken = new Scanner(System.in);
while (sken.hasNext() && !sken.equals("exit")) {
String[] line = sken.nextLine().split(",");
String name = line[1];
int howOld = Integer.parseInt(line[0]);
hashMap.put(howOld, name);
}
System.out.println("Input Complete!");
System.out.println("HeshMap input:");
System.out.println(hashMap + "\n"); // <-- this line
Map<Integer, String> treeMap = new TreeMap<>(hashMap);
System.out.println("Sorted by years:");
System.out.println(treeMap);
}
Also, I'm sure that the line I marked with comment won't print properly, how is the proper way to print a HashMap?
Reason of Exception
Following line cause of occurrences java.lang.ArrayIndexOutOfBoundsException: 1
because you are trying to sken.nextLine().split(",");
I the string entered does not contain ,
in it you cannot get line[1];
String[] line = sken.nextLine().split(",");
How about refactoring code
Your input should contain ,
character as per your logic, and exit will be work like this.
while(sken.hasNext())
{
String thisLine = sken.nextLine();
if(thisLine.equals("exit")){
break;
}
String[] line =thisLine.split(",");
String name= line[1];
int howOld= Integer.parseInt(line[0]);
hashMap.put(howOld, name);
}
More
May be helpful for you ;)
while(true)
{
System.out.println("Please Enter Age:");
int howOld = sken.nextInt();
System.out.println("Please Enter Name:");
String name = sken.next();
String thisLine = sken.nextLine();
hashMap.put(howOld, name);
System.out.println("Do you want the results (Y/N)?");
String more= sken.next();
if(more.equals("N") || more.equals("n")){
break;
}
}
String name= line[1];
This above line is the Culprit , you are accessing index 1
without checking that even if it exist or not .
If your input string does not contain any comma as delimiter ,
then you'll surely get this Exception , So it's better to check before accessing
if(line.length==1){ // then Access index
}
Always have a try catch handler check for handling exceptions such as this.
try{
String[] line = sken.nextLine().split(",");
String name= line[1];
int howOld= Integer.parseInt(line[0]);
hashMap.put(howOld, name);
} catch (ArrayIndexOutOfBoundsException iobe) {
// do something here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.