I\'m creating an int array secretNumber. When I declare the array size as a number, there\'s no out of bounds exception, but when I declare the array size with a variable (numDi
As others have commented on you are creating the array with a variable, but that variable is left to the default integer value, which is 0. Instead, don't make the array until you know the size you want. This will fix your issue.
public class Engine {
public int numDigits;
public int[] secretNumber; // leave empty
public Random randomNumberGenerator;
public void setNumDigits() {
Scanner setNumDigits = new Scanner(System.in);
System.out.println("Enter the number of digits to use");
String numDigits = setNumDigits.nextLine();
this.numDigits = Integer.parseInt(numDigits);
secretNumber = new int[this.numDigits]; // build it here
}
}
As a final note, what happens to your code if I enter a string or a double instead of an integer? It's always a good idea to consider common use cases like that.