0

I'm trying to test this by converting the Yen and the USD both ways using an if-else statement. My output is always 0, and it seems like the if-else statement in the "conversion" method isn't doing what I want it to do.

import java.util.Scanner;

    public class CurrencyConverter {
    private Scanner sc;
    private String currency;
    private String currency2;
    private int amount;
    private int amount2;

    public void getCurrency() {
        System.out.println("Please enter the currency and the amount you want to convert.");
        sc = new Scanner(System.in);
        currency = sc.next();
        amount = sc.nextInt();

        System.out.println("Please enter the currency you want to convert to.");
        currency2 = sc.next();
    }

    public void conversion() {
        if(currency == "usd" && currency2 == "yen") 
            amount2 = amount * 146;
        else if(currency == "yen" && currency2 == "usd") 
            amount2 = amount / 146;
        System.out.println(amount2);
    }
    public static void main(String[] args) {
        CurrencyConverter money = new CurrencyConverter();
        money.getCurrency();
        money.conversion();
    }
}

I tried moving the logic in the "conversion" method into the "getCurrency" method with no success. I'm also open to other, more efficient ways of starting to build a program like this.

  • It doesn't address the base issue of this question, which was about how to compare two `String` Objects. But, you also asked for advice on building a program like this. Suppose you want to add more currency types. With this design, as currency types are added, the chain of `if` statements will grow. What would you do, for example, if your program had 20 currencies? Here are suggestions: 1) Java is an Object-Oriented-Programming language. Consider creating a `Currency` class. 2) Consider using a `Map ` (i.e., name, conversion rate). 3) Consider using `enum` – Old Dog Programmer Aug 31 '23 at 02:32
  • @OldDogProgrammer I've worked with classes, maps, and I've used "enum" before as well. I'll check out your tip. Thanks for the comment. – Programmer1 Aug 31 '23 at 03:09

0 Answers0