2015-05-22 19 views
2

我正在寫一個使用JOptionPane而不是掃描器的二次公式。其中一個變量(行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); 
     } 

    } 
} 
+0

還要注意的是'System.exit(0); }'應該'System.exit(0);'.. –

回答

3

你需要做的

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

在所有在其中輸入輸入不同的情況。

+0

非常感謝你!我覺得這樣的新手,所以我感謝你的幫助。 – Autre

0

在方法中聲明的所有變量都需要在使用它們之前進行初始化,因爲它們沒有默認值(如類成員)。

0

您的變量userInput保留爲空。

您應該保存在userInput變量的用戶輸入,試試這個:

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

它的工作,現在我只是要測試。感謝您的迴應! – Autre

相關問題