因此,我有下面的代码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);
}
你可以做这样的事情:
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
}
}
}
您可以使用< code>Scanner的< code>hasNext()函数,在有更多输入时继续读取,而不进行其他提示。尝试:
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();
}
}