Declaring array size with variable leads to out of bounds exceptiong

后端 未结 2 452
情歌与酒
情歌与酒 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:04

    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.

提交回复
热议问题