Java Constructor variables being ignored

前端 未结 7 1134
我在风中等你
我在风中等你 2021-01-27 05:54

I am trying to create a instance of the object Iset. When the person makes the object they have to give an int which will be the size of a boolean array that will store a set of

7条回答
  •  梦谈多话
    2021-01-27 06:21

    You are not initializing the size instance variable properly, instead you are initializing a local variable size. Therefore your size instance variable remained initialized with 0 and your seti instance variable is an empty array causing the out of range error.

    As pointed out by others, you don't need the instance variable size.
    There is also no need for another local variable size inside your constructor, Just use seti.length to determine the size of the array. To simplify, your code should be:

    public class Iset {
    boolean[] seti;
    
    ISet(int a) {
        seti = new boolean[a];
    

    I would recommend you use static analysis tools like checkstyle to eliminate bug like this in your codes.

提交回复
热议问题