在java中从用户获取整数数组输入

Faw*_*kes 2 java string java.util.scanner

我需要从用户那里获得一系列整数.系统不会提示用户输入数字.输入将具有以下形式:

6

34 12 7 4 22 15

3

3 6 2

第一行表示第二行中的整数数.我首先尝试将第二行作为String读取,然后使用StringTokenizer将其分解为代码中的整数.正常情况发生在我的程序中很多,这很耗时,我需要直接阅读它们.我记得在C++中它过去相当简单.以下代码段用于执行此操作.

for(i=0;i<6;i++)
cin>>a[i];
Run Code Online (Sandbox Code Playgroud)

为此,我使用了java.util.Scanner,我的代码如下所示:

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Scanner src = new Scanner(System.in);

for(x=0;x<2;x++){
    arraySize = Integer.parseInt(br.readLine());

    for(i=0;i<arraySize;i++)
        array[i] = src.nextInt();
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我收到以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "34 12 7 4 22 15"
Run Code Online (Sandbox Code Playgroud)

我愿意接受建议,而不是仅仅依靠Scanner.如果有任何其他方法来实现这一点,我就是游戏.

bla*_*nda 10

为了将来参考,以下是使用Scanner该类的方法:

import java.util.Arrays;
import java.util.Scanner;


public class NumberReading {
    public static int [] readNumsFromCommandLine() {

        Scanner s = new Scanner(System.in);

        int count = s.nextInt();
        s.nextLine(); // throw away the newline.

        int [] numbers = new int[count];
        Scanner numScanner = new Scanner(s.nextLine());
        for (int i = 0; i < count; i++) {
            if (numScanner.hasNextInt()) {
                numbers[i] = numScanner.nextInt();
            } else {
                System.out.println("You didn't provide enough numbers");
                break;
            }
        }

        return numbers;
    }

    public static void main(String[] args) {
        int[] numbers = readNumsFromCommandLine();
        System.out.println(Arrays.toString(numbers));
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

你说你可以在 C++ 中使用以下代码:

for(i=0;i<6;i++) 
cin>>a[i];
Run Code Online (Sandbox Code Playgroud)

如果这是您在 C++ 中使用的,为什么不直接使用它呢?

for(i=0;i<6;i++)
a[i] = input.nextInt();
Run Code Online (Sandbox Code Playgroud)

假设扫描仪声明是:

Scanner input = new Scanner(System.in);
Run Code Online (Sandbox Code Playgroud)

据我所知,人们正在尝试为您编写整个程序。但正如您所说,您可以使用 C++ 代码解决这个问题,我只是为您将代码转换为 Java。

如果你想要完整的代码,这里是:

import java.util.Scanner;

public class arrayFun {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Create a new array. The user enters the size
        int[] array = new int[input.nextInt()];

        // Get the value of each element in the array
        for(int i = 0; i < array.length; i++)
            array[i] = input.nextInt();

        /* Note that the user can type the following:
         * 6
         * 34 12 7 4 22 15
         * This will set the array to size 6
         * array[0] = 34;
         * array[1] = 12;
         * etc.
         */

    }

}
Run Code Online (Sandbox Code Playgroud)

我意识到这个回应已经晚了好几年了,但当我遇到这个问题时,我正在寻找一个不同的问题。这里的答案让我非常困惑,直到我意识到这不是我想要的。看到这个仍然出现在谷歌上,我决定发布这个。