货币转换器If InputDialogs的语句

时间:2016-02-04 22:54:50

标签: java

我的项目是创建货币转换器,我似乎无法将if语句连接到用户的选择。

import javax.swing.JOptionPane;

public class Test {



    public static void main(String args[]){

    double CanadianDollar = .9813;
    double Euro = .757;
    double IndianRupee = 52.53;
    double JapaneseYen = 80.92;
    double MexicanPeso = 13.1544;
    double BritishPound = .6178;

    String input; 
    Object[] possibilities = {"Canadian Dollar", "Euro", "Indian Rupee", "Japanese Yen",
            "Mexican Peso", "British Pound"};
    String currencyChosen = (String) JOptionPane.showInputDialog( null,
         "What currency would you like to start with?:",
         "Currency Converter",
         JOptionPane.QUESTION_MESSAGE,
         null,
         possibilities,
         null);

    JOptionPane.showMessageDialog(null, "You chose to start from " + currencyChosen);

    Object[] possibilitiesToChoose = {"Canadian Dollar", "Euro", "Indian Rupee", "Japanese Yen",
            "Mexican Peso", "British Pound"};
    String convertTo = (String) JOptionPane.showInputDialog( null,
         "What currency would you like to convert to?:",
         "Currency Converter",
         JOptionPane.QUESTION_MESSAGE,
         null,
         possibilities,
         null);

    JOptionPane.showMessageDialog(null, "You chose to convert from " + currencyChosen + " to " + convertTo);


    if (currencyChosen = "Canadian Dollar")   <- This is not working

    }
}

2 个答案:

答案 0 :(得分:1)

尝试替换它:

 if (currencyChosen = "Canadian Dollar") 

使用equals方法:

  if ("Canadian Dollar".equals(currencyChosen )) 
   ...

用于赋值的=不是用于检查字符串之间的相等性。

答案 1 :(得分:1)

在比较Java中的字符串时,您需要使用equals方法

if(string1.equals(string2))

因为string1和string2可能具有相同的值但不引用同一个对象。

if(string1 == string2)
如果string1和string2实际引用同一个对象

将仅返回true

你可以在中阅读 Java String documentation

(编辑:您的代码实际上将值“Canadian Dollar”分配给currencyChosen。请注意“=”和“==”之间的差异)