Home > Blockchain >  How do I call a certain element in an array, using a user input?
How do I call a certain element in an array, using a user input?

Time:04-07

public static int gShelterSize;

public static void main (String[] args){
    Scanner s = new Scanner(System.in);
    System.out.println("UTSA - Spring2022 - CS1083 - Section 004 - Project 2 - TexasShelter - written by Reid Boulet");
    System.out.print("Please, enter the number of dogs in the shelter (Max 100): ");
    gShelterSize = s.nextInt();
    mainMenu();
}

public static double[] gWeight = new double[gShelterSize];

public static void assignModifyDog(double gWeight[], int gShelterSize){
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the current index(0 to " gShelterSize ") : ");
    int index = 0;
    index = s.nextInt();
    System.out.println("The current weight of the dog at " index " is : " gWeight[index]);
    System.out.print("Enter the weight of the new dog (0.00 - 100.00) : ");
    double currentWeight = s.nextDouble();
    if(0 < currentWeight && currentWeight <= 100){
        currentWeight = gWeight[index];
    }else{
        System.out.println("Value out of range, please, try again.");
        assignModifyDog(gWeight,gShelterSize);
    }
}

Whenever I compile and run the program it gives me a bunch of errors whenever it reaches gWeight[index] in the println
Errors:

java.lang.ArrayIndexOutOfBoundsException: 3
    at testProject2.assignModifyDog(testProject2.java:66)
    at testProject2.mainMenu(testProject2.java:30)
    at testProject2.main(testProject2.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

CodePudding user response:

You don't have the implementation of the mainMenu() method, so I can only guess at the contents of it. Assuming that the gWeight array and the gShelterSize variable are the static variables that you've defined, here's the problem: the gShelterSize is initialised to 0 until it's assigned in the main() method. The gWeight array is thus initialised to a zero-length array. Although it's defined after the main() method, it is initialised before the main() method runs. So unless it's being assigned somewhere else, it will always be a zero-length array, and gWeight[x] will throw an ArrayIndexOutOfBoundsException for any value of x, even 0.

CodePudding user response:

what is 'mainMenu()' method. use num-1(when ever work with array because array always atart with 0 index) for avoid 'ArrayIndexOutOfBoundsException' error

  •  Tags:  
  • java
  • Related