所以我有以下chuckj代码和我想要它做的是用户在netbeans控制台中输入5个数字。我想这样做的方式是他可以输入一些通过分配数字与空格或逐行显示如下
但我想要的是“输入一串数字”只有在需要时才可见,例如当他需要输入下一个数字时。有可能这样做吗?
以下代码
完成以下操作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);
}
答案 0 :(得分:2)
你可以这样做:
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
}
}
}
答案 1 :(得分:0)
您可以使用hasNext()
Scanner
函数在没有其他提示的情况下继续阅读。尝试:
Scanner reader = new Scanner(System.in);
int number;
ArrayList<Integer> numbers = new ArrayList<Integer>();
int i = 0;
while((i < 5))
{
System.out.println("Enter a string of numbers:");
if(reader.hasNextLine())
{
String[] numbersRead = reader.nextLine().split("\\s");
System.out.print("Read:");
for(int n = 0; n < numbersRead.length; n++)
{
numbers.add(Integer.parseInt(numbersRead[n]));
i++;
}
System.out.println();
}
}