Reputation:
I don't understand why this is going out of bounds, can you help me?
What should happen:
For some reason after the first item in the list it goes out of bounds but I can't tell why.
import java.util.Scanner; //import scanner
public class project2 {
public static void main (String[] args){
Scanner input = new Scanner(System.in); //scanner for input
int a = 0;
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
System.out.println("How long are the lists? ");
System.out.print("(The lists should be the same length): ");
a = input.nextInt();
int count=1;
System.out.println("Enter numbers for list A:");
for(int j = 0; j < a-1 ; j++){ //user input numbers loop into array "list"
System.out.print(count + ": ");
lista[j] = input.nextDouble();
count++;
}
}
}
Upvotes: 0
Views: 110
Reputation: 240908
you created array with 0 element and if you enter any number for a which is greater than 1 it will attempt to look at index 1 which is out of bound
Upvotes: 3
Reputation: 178263
When you declare your lista
and listb
arrays, you use a
as the length, but at that time, it's 0
. You haven't assigned the user's value to a
yet.
Create your arrays after you have the length from the input.
a = input.nextInt();
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
Upvotes: 5