【问题标题】:Variable is unused one instance but not in another变量在一个实例中未使用,但在另一个实例中未使用
【发布时间】:2015-05-22 17:29:40
【问题描述】:

我正在使用 JOptionPane 而不是 Scanner 编写二次公式。其中一个变量(第 12 行和第 17 行,userInput)被标记为未声明,从而产生运行时错误。其他迭代似乎没有这个问题。我是初学者,但我尝试过使用我手头的资源,但运气不佳。谁能看到我哪里出错了?

/*

*/
package a3main2;

import javax.swing.JOptionPane;

public class A3main2 
{
    public static void main(String[] args) 
    {
        String userInput;

        JOptionPane.showMessageDialog(null, "Hooray for quadratic fun!");
        JOptionPane.showInputDialog(null,"Enter the value for 'a': ");
        Double a = Double.parseDouble(userInput);
        JOptionPane.showInputDialog(null,"Enter the value for 'b': ");
        Double b = Double.parseDouble(userInput);
        JOptionPane.showInputDialog(null,"Enter the value for 'c': ");
        Double c = Double.parseDouble(userInput);

        Double discriminant = Math.sqrt((Math.pow(b , b))- (4 * a * c));
        Double part1 = ((-(b)) / (2 * a));
        Double x = ((-(b)) + Math.sqrt(discriminant) / (2 * a));
        Double y = ((-(b)) - Math.sqrt(discriminant) / (2 * a));

        if (discriminant < 0)
        {
            JOptionPane.showMessageDialog(null, "The two roots are " + x + "i" + 
                    " and " + y + "i.");
        }          
        else if (discriminant > 0)
        {
            JOptionPane.showMessageDialog(null, "There are two roots: " + x + 
                    " and " + y + ".");
        }
        else if (discriminant == 0)
        {
            JOptionPane.showMessageDialog(null, "There is only one root: " + x + 
                    ".");
        }
        else if (a == 0)
        {
            JOptionPane.showMessageDialog(null, "There is only one root: " + part1 
            + ".");
        }
        System.exit(0);
        }

    }
}

【问题讨论】:

  • 还要注意System.exit(0); } 应该是System.exit(0); ..

标签: java string swing variables


【解决方案1】:

你需要做的

userInput = JOptionPane.showInputDialog(null,"Enter the value for 'a': ");
Double a = Double.parseDouble(userInput);  

在输入输入的所有不同情况下。

【讨论】:

  • 哇,非常感谢!我觉得自己像个新手,所以非常感谢您的帮助。
【解决方案2】:

在方法中声明的所有变量都需要在使用它们之前进行初始化,因为它们没有默认值(如类成员)。

【讨论】:

    【解决方案3】:

    您的变量 userInput 保持为空。

    您应该将用户输入保存在 userInput 变量中,试试这个:

    userInput = JOptionPane.showInputDialog(null,"Enter the value for 'a': ");
    

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2023-03-28
      • 2013-07-02
      • 2023-03-08
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      相关资源
      最近更新 更多