Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)
 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading