gpt4 book ai didi

java - 在控制台中输入多个数字

转载 作者:行者123 更新时间:2023-12-02 05:06:41 26 4
gpt4 key购买 nike

所以我有以下的chuckj代码,我想要它做的是让用户在netbeans控制台中输入5个数字。我想要做的方式是他可以通过用a分隔数字来输入一些数字空格或逐行,例如如下所示

enter image description here

但我想要的是“输入一串数字”仅在需要时才可见,例如当他需要输入下一个数字时。可以这样做吗?

下面是通过下面的代码完成的

Scanner reader = new Scanner(System.in);
int number;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 5; i++) {
System.out.println("Enter a string of numbers");
number = reader.nextInt();
numbers.add(number);
}

System.out.println("size" + numbers.size());
for(int takenNumber : numbers){
System.out.println(takenNumber);
}

最佳答案

你可以这样做:

Scanner reader = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();

int numbersEntered = 0; // Stores how many numbers the user has entered so far
while (numbersEntered < 5) { // Keep asking if they have not entered 5 numbers yet
System.out.println("Enter a string of numbers");
String[] input = reader.nextLine().split(" "); // Split the input by spaces into an array
numbersEntered += input.length; // Add the number of numbers they entered to the variable
for (int i = 0; i < input.length; i++) {
if (numbers.size() < 5) { // Only add the numbers if the list is not full
numbers.add(Integer.parseInt(input[i])); // Add each number they entered to the numbers list
}
}
}

关于java - 在控制台中输入多个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com