3 回答
TA贡献1848条经验 获得超10个赞
我认为您的逻辑应该是从扫描仪读取整个输入行。然后,进行完整性检查以确保它只有两个由空格分隔的术语。如果是这样,则将单词和数字分配给它们各自的数组。
System.out.println("Write a name and number (separate with blankspace), end with 'q'");
while (true) {
String full = in.nextLine();
if ("q".equals(full)) {
break;
}
String[] parts = full.split("\\s+");
if (parts.length != 2) {
// you could also just break here as well, but throwing an exception
// is something you might actually do in a production code base
throw new IllegalArgumentException("Wrong number of input terms; use 2 only");
}
listNames.add(parts[0]);
listNumbers.add(Integer.parseInt(parts[1]));
}
TA贡献1786条经验 获得超11个赞
使用 String.split() 函数会更容易得到你想要的。
正如您所提到的,输入由空格分隔。假设输入是“Jordan 19”,那么您可以使用如下内容:
String [] data = full.split(" "); //split the input by a blank space
listNames.add(data[0]); //data[0] = Jordan
listNumbers.add(Integer.parseInt(data[1])); //data[1] = 19
如果您的所有输入都是一个字符串,然后是一个数字,这应该可以工作
TA贡献1725条经验 获得超8个赞
ArrayLists 从索引 0 开始。因此,如果要输出 ArrayList 中的第一个 Item,则必须编写System.out.println(listNames.get(0));
添加回答
举报
