Search code examples
javaarraysinput

unable to fill an array with numbers from input in java


I'm trying to set an array with desired length of numbers. It has to get the numbers from user but it throws an exception error after getting the first one. Can anyone help me to fix this please?

import java.util.Scanner;

public class t4NumericalOperations {
    Scanner input = new Scanner(System.in);
    int n;
    double[] numbers = new double[n];

    public void readNumbers(){
        System.out.println("How many numbers do you want to do caculations on? ");
        n = input.nextInt();
        System.out.println("Enter your numbers : ");
        for(int i=0;i<n;i++){
            numbers[i] = input.nextDouble();
        }
    }
}

class testSum{

    public static void main(String[] args) {
        t4NumericalOperations col1 = new t4NumericalOperations();
        col1.readNumbers();
        col1.calculate();
        col1.display();
    }
}

The output is like this:

How many numbers do you want to do caculations on? 
2
Enter your numbers : 
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at exercises1.ch4.t4NumericalOperations.readNumbers(t4NumericalOperations.java:15)
        at exercises1.ch4.testSum.main(t4NumericalOperations.java:36)
 

Solution

  • You must declare the variable as an instance variable, but allocate the array after the number is read.

    public class t4NumericalOperations {
        Scanner input = new Scanner(System.in);
        int n;
        double[] numbers;   // declaration only
    
        public void readNumbers(){
            System.out.println("How many numbers do you want to do caculations on? ");
            n = input.nextInt();
            numbers = new double[n];  // allocate the array here
            System.out.println("Enter your numbers : ");
            for(int i=0;i<n;i++){
                numbers[i] = input.nextDouble();
            }
        }
    }