i'm trying to read in student information in one line, the line contains ID, name, age and gpa. I want to split the line by spaces and store each token in my string array Splited[]. Why does this code give me ArrayOutOfBounds error on the line String name = splited[1];
? Sample input: 3844 Jim 30 3.4
thank you
String [] splited = new String [4];
System.out.println("Enter student Id, name, age and gpa: ");
String info = keyboard.next();
//separate student info line by spaces
splited = info.split("\\s");
int id = Integer.parseInt(splited[0]);
String name = splited[1];
int age = Integer.parseInt(splited[2]);
double gpa = Double.parseDouble(splited[3]);
String info = keyboard.next();
is returning the first String
separated by a white space (so that would be id
) in your case.
Try using String info = keyboard.nextLine();
which will return the entire content up to the new line character. Then you can use String#split
(or another Scanner
) to parse the text
why don't you simply use " " instead of "\\s" to split the input. and you should check the validity of the input.
actual problem is: keyboard.next() only reads the next word (space is a defaultdelimiter of the scanner). use keyboard.nextLine() instead.
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.