为什么我会收到一条错误,指出可能无法初始化变量半径?

时间:2017-09-06 23:39:00

标签: java

目的是创建一个构造函数,它接受两个变量并确保它们在正确的范围内(> 0)。还要将iceCreamHeight初始化为0。

public class Cone {
    private final double radius;    // doesn't change after Cone is constructed 
    private final double height; // doesn't change after Cone is constructed
    private double iceCreamHeight;  
    public Cone(double radius, double height){
        iceCreamHeight = 0; 
        double r = radius; 
        double h = height;
        if(r <=0 || h <=0 || iceCreamHeight <= 0){
            r =1;
            h=1;
            System.out.println("ERROR Cone");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

在此计划中,您没有尝试更改heightthis的值。使用public class Cone { private final double radius; private final double height; private double iceCreamHeight; public Cone(double radius, double height){ this.iceCreamHeight = 0; this.radius = radius; //Uses 'this' this.height = height; if(this.radius <= 0 || this.height <= 0 || this.iceCreamHeight <= 0){ this.radius = 1; this.height= 1; System.out.println("ERROR Cone"); } } } 关键字来引用变量:

div{   
    position:fixed;
    z-index: 2;
    color: white;  /* Fallback: assume this color ON TOP of image */
    background: url('https://placekitten.com/g/500/500') repeat;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-size: 100px;
    font-weight: 800;
    text-transform: uppercase; 
    text-shadow: 2px 3px 8px rgba(59, 37, 17, 0.35) inset; 
}

答案 1 :(得分:0)

构造函数的参数总是局部变量;在这种情况下,它们恰好与实例变量具有相同的名称,但参数和实例变量并不相同。你必须有一个显式的赋值语句来设置局部变量;要么将参数名称更改为不同的名称(例如,只需使用rh作为参数名称,例如

public Cone(double r, double h) {
    // check the parameters here
    // note that you can assign new values to r and h; there's
    // no reason to declare separate variables to hold the same value
    radius = r;
    height = h;
}

,或使用this.radiusthis.height访问实例变量,例如

public Cone(double radius, double height) {
    // check the parameters here
    this.radius = radius;
    this.height = height;
}