2 回答
TA贡献1858条经验 获得超8个赞
您可以简单地拆分行并将值放在单独的列表中:
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
String arr[] = line.split(" ");// spiting the line based on space
if (arr.length==4) { // check if length is 4 as you are expecting
// use Integer.valueOf() to convert from string to Integer
power.add(arr[0]);
energy.add(arr[1]);
idea.add(arr[2]);
strength.add(arr[3]);
}else {
//throw exception or break
}
input += line + "\n";
}
TA贡献1833条经验 获得超4个赞
您可以使用此程序输入任意多的值:
List<Integer> power = new ArrayList<>();
List<Integer> energy = new ArrayList<>();
List<Integer> idea = new ArrayList<>();
List<Integer> strength = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
String s = sc.nextLine();
if(s.equals("exit")) break;
String args = s.split(" ");
if(args.length >= 4) {
power.add(Integer.valueOf(args[0]));
energy.add(Integer.valueOf(args[1]));
idea.add(Integer.valueOf(args[2]));
strength.add(Integer.valueOf(args[3]));
}
}
添加回答
举报