0

I am writing a program to determine the cost of gasoline, given the price-per-gallon and the amount of gallons purchased, but also given the payment method (cash or credit). To read the payment method, I have defined a String named paymentMethod as the third argument input in the command line, as shown below:

    public class gas{
    public static void main(String[] args){
        double pricePerGallon=Double.parseDouble(args[0]);
        double gallonsPurchased=Double.parseDouble(args[1]);
        String paymentMethod=args[2];
        String cash="cash";
        String credit="credit";
        if (pricePerGallon>0 && gallonsPurchased>0){
            **if (paymentMethod==cash)**
            {
            System.out.println(pricePerGallon*gallonsPurchased);
            }
            else if (paymentMethod==credit)
            {
            System.out.println(1.1*pricePerGallon*gallonsPurchased);
            }
        }
        else{
            System.out.println("Error");
        }
    }
}

I'm seeing if the third argument (which is a string) is the string "cash", in which case the cost of the gas is calculated and printed. If it is credit, there's an additional 10% charge.

Problems are arising with the boolean " (paymentMethod==cash) ". My program is compiling and I can run it but when I hit enter, nothing is returned. Not even the computation of the price.

Jee Mok
  • 6,157
  • 8
  • 47
  • 80
  • Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Vineet Kulkarni Sep 22 '19 at 04:15

1 Answers1

0

You need to use the equals method. The == operator does not work on Strings in Java as you would want it to.

Change:

if (paymentMethod==cash)

to

if (paymentMethod.equals(cash))

And similarly for the credit conditional also.