Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么会出现一个错误,说变量半径可能未初始化?_Java - Fatal编程技术网

Java 为什么会出现一个错误,说变量半径可能未初始化?

Java 为什么会出现一个错误,说变量半径可能未初始化?,java,Java,其目的是创建一个构造函数,该构造函数接受两个变量,并确保它们位于>0的正确范围内。还可以将冰淇淋高度初始化为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 doub

其目的是创建一个构造函数,该构造函数接受两个变量,并确保它们位于>0的正确范围内。还可以将冰淇淋高度初始化为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");
        }
    }
}

在本程序中,您不会尝试更改半径或高度的值。使用this关键字引用变量:

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");
        }
    }
}

构造函数的参数总是局部变量;在本例中,它们恰好与实例变量具有相同的名称,但参数和实例变量不相同。必须有一个显式赋值语句来设置局部变量;或者将参数名称更改为不同的名称,例如,只需使用r和h作为参数名称,例如

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.radius和this.height访问实例变量,如

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

您不明白错误消息是什么吗?半径和高度仍然可以是最终的,这样做可能是可取的,以确保构造函数之外的任何内容都不能更改它们。最终字段是一件非常好的事情。解决这个问题有比删除有益内容更好的方法。@VGR当我写这个答案时,我不知道最终字段可以在对象的构造函数中设置。最新答案