2017-07-21 54 views
0

我正在爲德國即將舉行的選舉編寫一個小小的選舉計劃。那麼,它不工作。使用JOptionPane的Java選舉程序

public static void main(String[] args) 
{ 
    String _Kandidat1; 
    String _Kandidat2; 

    _Kandidat1 = JOptionPane.showInputDialog("Do you Vote for the AFD or for the CDU ?"); 
    if (_Kandidat1 == "AFD") 
     System.out.println("The AFD won the election!"); 
    else 
     System.out.println("The CDU won the election!"); 
    } 
} 

如果我輸入「AFD」它說CDU贏了。如果我在任何情況下輸入「CDU」。 我不確定,但我認爲這個錯誤在if (_Kandidat1 == "AFD")

任何解決方案?

+1

使用'.equals()'方法 – XtremeBaumer

回答

4

您需要使用等號,否則你比較基準:

_Kandidat1.equals("AFD") 
1

應該首先閱讀的Java文檔String類。這個類不是原始類型,因此平等不應該與==檢查。您應該使用.equals()方法檢查字符串是否相等。

if (_Kandidat1.equals("AFD")) 
    System.out.println("The AFD won the election!"); 
else 
    System.out.println("The CDU won the election!"); 
}