Declaring array size with variable leads to out of bounds exceptiong

后端 未结 2 424
情歌与酒
情歌与酒 2021-01-27 02:47

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 03:05

    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];
    }
    

提交回复
热议问题