user8360486 user8360486 - 3 years ago 72
Java Question

Why is the scanner function not working?

So this code takes the value of n and returns a list of divisors as well as the total number of divisors. If I remove the

Scanner
declaration and its assignment to int n and simply give int n a value, the code runs perfectly.

However, as it is, it returns this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Program.main(Program.java:25)


I have no idea what the problem is.

import java.util.Scanner;
public class Program{
static int n;
static int x = 1;
static int [] arr = new int[n];
static int q = 0;
static int g = 0;
static int p = 1;
static int count;


public static void main(String[] args){

Scanner scan = new Scanner(System.in);
int n = scan.nextInt();

while(x <= n){

arr [q] = p; //assigns value to each array index
g = n%arr[q]; // stores value of remainder
q++;
p++;
x++;
if (g == 0){ //counts and displays each time remainder = 0
count++;
System.out.println(q);
}

}

System.out.println(count + " Divisors");


}
}

Answer Source

The size of arr is declared when n still holds no value(before the size is inputted). Do this:

import java.util.Scanner;

public class Program {
    static int n;
    static int x = 1;
    static int [] arr; //no size set
    //...
    //Other variables
    //...

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        arr = new int[n]; //Now the size is set to the inputted number.
        while(x <= n) {
            //...
            //Other code to find divisors
            //...
        }
    }
}

You need to name the size of arr after you input the n, otherwise the size is set to 0, causing the ArrayIndexOutOfBoundsException.

This line:

arr[q] = p;

Is what actually caused the error. arr[q] couldn't hold a value, because there was no arr[q]. the array had no size, so it couldn't hold any members.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download