简体   繁体   中英

Local variable may not have been initialized

Code:

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

Error:

The local variable x1 may not have been initialized

at line 9

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

When you do an assignment, the right-hand part of that assignment is evaluated first , so it first will evaluate

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

at that moment, x1 has not been initialized nor declared. Therefore, you cannot use it. After the right-hand part gets evaluated, then its result is assigned to the left-hand part :

String x1 = result;

How to fix it? One simple way, would be deleting x1 so you get

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

Notes:

  • You may want to check that loop condition while (rand == rand)

You can not declare a variable and use it from same line:

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

You are attempting to use x1 before it was even assigned a value. You could, for example, initialize it to an empty string . eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM