在控制台中输入多个数字

Enter multiple numbers in console

所以我有以下 chuckj 代码,我想要它做的是让用户在 netbeans 中输入 5 个数字 console.The 我想这样做的方式是他可以通过 separting 输入一些数字带有 space 或逐行的数字,例如如下所示

但我想要的是 "Enter a string of numbers" 仅在需要时可见,例如当他需要输入下一个数字时。可以这样做吗?

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

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);
        }

您可以使用ScannerhasNext()功能,在有更多输入的情况下继续阅读,而无需进行其他提示。尝试:

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();
  }
}

你可以这样做:

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
        }
    }
}