Вопрос

I don't understand why this is going out of bounds, can you help me?

What should happen:

  • user inputs length of list
  • user inputs all items in the list, only prompted until the user-inputed length of list (a) is reached.

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++;
    }
    }
}
Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top