从键盘读取值以将它们保存到数组

Reading values from keyboard ​to save them to an array

想法是从键盘输入数字并将它们保存到数组中:

public void set_numbersQ() {
    ArrayList<int[]> lf = new ArrayList<>();
    int[] fraction= new int[1];
    for(int i = 0; i < 2; i++){
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            fraction[i] = Integer.valueOf(br.readLine());
        }
        catch(Exception e){} 
    }
    lf.add(fraction);
    System.out.println(fraction[0] + " / " + fraction[1] );

}

这段代码给我一个错误:

java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1.

因为 fraction[0] 保存正确但 fraction[1] 不是。我认为错误可能在 InputStreamReaderBufferedReader 中,因为 try 已正确执行。

流 reader 应立即打开,fraction 大小必须为 2

    public static void set_numbersQ() {
        int[] fraction = new int[2];
        try (InputStreamReader input = new InputStreamReader(System.in)) {
            Scanner scanner = new Scanner(input);
            fraction[0] = scanner.nextInt();
            fraction[1] = scanner.nextInt();
            System.out.println(fraction[0] + " / " + fraction[1] + " = " + (fraction[0] / fraction[1]));
        } catch (Exception ex) {

        }
    }