java - 编译失败-静态变量示例

标签 java compiler-errors

在JAVA中执行以下程序时,在第14行出现错误。请您能帮助我为什么?

public class Triangle{

static double area;
int b=2, h=3;
     public static void main(String []args){
        System.out.println("Static variable" +area);
        double p,b,h;
        if (area==0){
            b=3;
            h=4;
            p=0;
            System.out.println("sos");
        }
        area = p*b*h;
        //System.out.println("Area is "+ area);
     }
}

o/p编译失败:
$javac Triangle.java
Triangle.java:14: error: variable p might not have been initialized
        area = p*b*h;
               ^
Triangle.java:14: error: variable b might not have been initialized
        area = p*b*h;
                 ^
Triangle.java:14: error: variable h might not have been initialized
        area = p*b*h;
                   ^
3 errors

最佳答案

public class Triangle{

static double area;
int b=2, h=3;
     public static void main(String []args){
        System.out.println("Static variable" +area);
        double p,b,h;
        if (area==0){
            b=3;
            h=4;
            p=0;
            System.out.println("sos");
        }
        area = p*b*h;
        //System.out.println("Area is "+ area);
     }
}

如果您想知道,这些整数将被忽略。
double p,b,h;

这些是使用的。它们仅在area == 0时初始化
它们必须针对每种情况进行初始化。改变
double p,b,h;

行到:
double p=0,b=0,h=0;

请记住:局部变量不会获取默认值。

编辑:另一个选项是移动该行:
area = p*b*h;

在if块中。

关于java - 编译失败-静态变量示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60429098/

相关文章:

每个选定项目的 JavaFX ComboBox 背景颜色

java - 从填充了 CheckMenuItems 的 MenuButton 访问信息 (JavaFX)

java - 无法在 Java 和 Selenium 中找到 iframe

opengl - G++。无法链接库

assembly - 在 NASM : "warning: attempt to initialize memory in BSS section ` . bss' 中使用 istruc 时:忽略 [-w+other]"

c++ - 虚幻 : "Unknown type name UTextRenderComponent" compile error while following tutorial

java - Spring 中的属性范围

java - 有效地查找对象数组中的元素

c++ - 无法从谷歌 Protocol Buffer 编译示例

hadoop - 无法在 Mahout 中实例化类型 Cluster、KMean 聚类示例