Search code examples
javabufferedreaderinputstreamreader

Reading values from keyboard ​to save them to an array


The idea is enters numbers from keyboard to save them into 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] );

}

This code give me an error:

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

Because fraction[0] is saved correctly but fraction[1] it's not. I think the error could be in InputStreamReader or in BufferedReader because the try is executed correctly.


Solution

  • Stream reader should be opened at once and fraction size must be 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) {
    
            }
        }