2 回答

TA貢獻1858條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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]));
}
}
添加回答
舉報