2013-02-20 25 views
1

我在這裏錯過了一些東西。我的程序在要求輸入他們的服務包後結束。請原諒冗餘代碼,我是一個初學者,並且還沒有學到比這更有效的方法。程序結束時沒有考慮到語句(編碼初學者)

import javax.swing.JOptionPane; 

public class InternetSP 
{ 
    public static void main(String[] args) 
    { 

     final double PACKA = 9.95, PACKB = 13.95, PACKC = 19.95; 
     final int PACKAC = 2, PACKBC = 1; 
     double chargecalc, entrycalc = 0; 
     String entry, pack; 

     pack = JOptionPane.showInputDialog(null, "Please enter your service" + " package (A,B or C)"); 
     if (pack == "A" || pack == "B") 
     { 
      entry = JOptionPane.showInputDialog(null, "Please enter your usage " + "hours."); 
      entrycalc = Double.parseDouble(entry); 
     } 

     if (pack == "A") 
     { 
      if (entrycalc > 10) 
      { 
       chargecalc = (PACKA + (entrycalc * PACKAC)); 
       JOptionPane.showMessageDialog(null, "Your total charges are: $" + chargecalc); 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(null, "Your total charge is: $" + PACKA); 
      } 
     } 
     else if (pack == "B") 
     { 
      if (entrycalc > 20) 
      { 
       chargecalc = (PACKB + (entrycalc * PACKBC)); 
       JOptionPane.showMessageDialog(null, "Your total charges are:" + "$ " + chargecalc); 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(null, "Your total charge is: $" + PACKB); 
      } 

     } 
     else if (pack == "C") 
     { 
      JOptionPane.showMessageDialog(null, "Your total charge is:" + "$ " + PACKC); 
     } 


     System.exit(0); 

    } 
} 
+0

是什麼讓你覺得他們是「不考慮」?你試圖調試什麼? – geoffspear 2013-02-20 13:28:10

+0

+1爲新,但仍然問一個問題! – Rich 2013-02-20 13:40:47

回答

2

你應該試試你的字符串與equals(或更好,equalsIgnoreCase)方法進行比較。

正如這裏所解釋的:在java中,「==」運算符檢查兩個變量是否指向相同的對象,而不是它們是否具有相同的值。

所以,如果你寫

String a1 = "A"; 
String a2 = "A"; 

然後

if (a1 == a2) { 
    // This is not executed 
} 
if (a1.equals(a2)) { 
    // This is executed 
} 

這是一個重要的區別,它存在於每一個對象,但大多數人都通過字符串欺騙,因爲它是第一個對象之一你比較。

通常人們通過比較數字開始,而在Java中,原始數字(int,long等)可以與==比較,因爲它們不是對象。

希望這會有所幫助,祝你好運!

+0

當然啦!謝謝! – Jim 2013-02-20 13:46:23