在构造函数中将布尔值设置为true

时间:2018-10-21 03:25:32

标签: java constructor boolean setter

对于我的第一个构造函数,我使用给定的参数初始化实例变量,而对于我的第二个构造函数,我需要将所有布尔值都设置为true,这就是我到目前为止所拥有的。

如何修复以下构造函数?因为我知道这有问题。

谢谢:)

公共课程尝试{

private boolean a;
private boolean b;
private boolean c;
private boolean d;


public Try (boolean a, boolean b boolean c, boolean d) {      
    this.a=a;
    this.b=b;
    this.c=c;
    this.d=d;
}


public Try() {
    boolean a = true;
    boolean b = true;
    boolean c = true;
    boolean d = true;

}

3 个答案:

答案 0 :(得分:1)

对于您的默认构造函数,我假设您正在尝试设置类属性,而不是设置在构造函数中声明的局部变量。如果是这样,您可能想要这样的东西:

public class Try {

    private boolean a;
    private boolean b;
    private boolean c;
    private boolean d;

    public Try (boolean a, boolean b boolean c, boolean d) {      
       this.a=a;
       this.b=b;
       this.c=c;
       this.d=d;
    }

   public Try() {
        this(true, true, true, true);
    }
}

答案 1 :(得分:0)

不要在构造函数中再次调用布尔变量。它已经被初始化。尝试在代码中进行以下修改:

void le_arquivo(char *optarg) {
    FILE *respostas;                
    char *arq;                      
    char resp[SBUFF];              
    char *tokens[SBUFF];           
    int c = 0;

    respostas = fopen(optarg, "r");
    if (respostas == NULL) {
        printf("Erro ao abrir o arquivo\n");
        return;
    }
    fgets(resp, sizeof(resp), respostas);
    arq = strtok(resp, "\n");      
    while (arq != NULL) {
        tokens[c] = arq;
        arq = strtok(NULL, "\n");
        c++;
    }
    fclose(respostas);
    organiza_dados(tokens, c);
} 

快乐编码。...

答案 2 :(得分:0)

我可以看到两个构造函数都有一些问题,下面将对此进行解释:

首先,一个逗号,在第一个构造函数的 boolean b 附近丢失,这将导致抛出错误( 4个错误)编译时间。将其替换为以下代码将解决这些错误:

public Try (boolean a, boolean b, boolean c, boolean d) {      
    this.a=a;
    this.b=b;
    this.c=c;
    this.d=d;
}

第二,当您仔细看一下第二个构造函数时,您会感觉到它只是初始化一些局部变量,这些局部变量在程序中的任何地方都不会使用,因此这只是编写了一些额外的代码行在对象创建和初始化过程中不会产生任何效果

如果不想在创建对象时初始化属性,则以下面的方式编写相同的代码将是初始化对象属性的好方法,或者只是使其为空,这也是一种好方法: / p>

 public Try() {
        this(true, true, true, true);
 }

public Try() {
a = true;
b = true;
c = true;
d = true;
}

(如果要求初始化为false

public Try() {}