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.
While we have already some clarification to the reason you got the exception there is still a question how to fix it and how to avoid such cases in future.
Let's go through your code step-by-step:
Engine engine = new Engine();
New engine
object is created an all class variables instantiated to their default values. Default value for primitive int
is 0;
At the moment of initialization you have:
public int numDigits; // 0
public int[] secretNumber = new int[numDigits]; // arrays object of size 0
public Random randomNumberGenerator; // null
How to proceed with that?
The issue is partially in object design - you need to identify the invariants that constrain the state variables. You need to set the size of the array during numDigits
initialization:
public int[] secretNumber; // null at the moment of object initialization
public void setNumDigits() {
Scanner setNumDigits = new Scanner(System.in);
System.out.println("Enter the number of digits to use");
numDigits = Integer.parseInt(setNumDigits.nextLine());
secretNumber = new int[numDigits];
}