我正在尝试在一行中读取学生信息,该行包含 ID、姓名、年龄和 GPA。我想用空格分割该行并将每个标记存储在我的字符串数组 Splited[] 中。为什么此代码在 String name = splited[1];
行上给出 ArrayOutOfBounds 错误?
输入示例:3844 Jim 30 3.4
谢谢
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();
返回由空格分隔的第一个 String
(因此将是 id
)在你的情况下。
尝试使用String info = Keyboard.nextLine();
,它将返回到新行字符的整个内容。然后您可以使用String#split
(或另一个Scanner
)来解析文本
关于java - 按空格分割字符串(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269800/