1

My project is to create a currency converter and I can't seem to connect an if statement to the choices of the user.

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

    }
}
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
jkjk
  • 101
  • 1
  • 3
  • 12

2 Answers2

1

Try to replace this:

 if (currencyChosen = "Canadian Dollar") 

With using equals method:

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

The = used for assign value not for check equality between string.

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
  • Thanks for the help. However, when I run the program it does not go through the "if" criteria. – jkjk Feb 04 '16 at 23:21
1

When comparing Strings in Java you need to use the equals method

if(string1.equals(string2))

because string1 and string2 might have the same value but not be referencing the same object.

if(string1 == string2)

will only return true if string1 and string2 are actually referencing the very same object

You can read about it in the Java String documentation

(edit: your code actually assigns the value "Canadian Dollar" to currencyChosen. note the difference between "=" and "==")

bdvll
  • 86
  • 6