局部变量可能尚未初始化

时间:2014-03-22 15:14:12

标签: java while-loop double

代码:

public static void main(String[] args) {
        double rand = 0;
        while (rand == rand) {
            double rand1 = Math.random();
            String x1 = javax.swing.JOptionPane.showInputDialog(null, rand1 + x1);
            if (x1.equals("exit")) {
                javax.swing.JOptionPane.showConfirmDialog(null, x1);
                System.exit(0);
            }
        }
    }

错误:

  

局部变量x1可能尚未初始化

第9行

  

String x1 = javax.swing.JOptionPane.showInputDialog(null,rand1 + x1);

3 个答案:

答案 0 :(得分:2)

当您执行作业时,该作业的右侧部分将首先评估 ,因此它首先会评估

javax.swing.JOptionPane.showInputDialog(null, rand1 + x1);

此时,x1尚未初始化或声明。因此,您无法使用它。在评估右侧部分之后,将其结果分配给左侧部分

String x1 = result;

如何修复?一种简单的方法就是删除x1以便

String x1 = javax.swing.JOptionPane.showInputDialog(null, rand1);

备注:

  • 您可能想要检查循环条件while (rand == rand)

答案 1 :(得分:1)

您无法声明变量并在同一行中使用它:

String x1 = javax.swing.JOptionPane.showInputDialog(null, rand1 + x1);
                                                                   ^ here

答案 2 :(得分:0)

您尝试在为x1分配值之前使用string。 例如,您可以将其初始化为空public static void main(String[] args) { double rand = 0; String x1 = ""; // first initialization while (rand == rand) { double rand1 = Math.random(); x1 = javax.swing.JOptionPane.showInputDialog(null, rand1 + x1); if (x1.equals("exit")) { javax.swing.JOptionPane.showConfirmDialog(null, x1); System.exit(0); } } } 。 e.g:

{{1}}