1

I'm learning Java and I'm struggling to understand why a simple program I'm wrting is not working the way it should.

import java.util.Scanner;

class CarApp{
String carMake;
String carColour;
String features;
int carPrice;

void carFinal(){
    System.out.println(carMake);
    System.out.println(carPrice);
    if(carMake == "ford")
    {
        carPrice = 120000;
    }
    else if(carMake == "porsche")
    {
        carPrice = 1000000;
    }
    System.out.println(carPrice);
    System.out.println("Thank you for choosing your car with the car chooser app!" + "\n");
    System.out.println("You have chosen a " + carColour + " " + carMake + " with " + features + "\n" );
    System.out.println("Your car will be delivered to you in 7 working days. At a price of R" + carPrice + ".");
}
}

public class App {
public static void main(String[] args) {
    Scanner carChooser = new Scanner(System.in);

    CarApp carApp = new CarApp();
    System.out.println("Please let us know which car you would like, porsche or ford:");
    carApp.carMake = carChooser.nextLine();
    System.out.println("Please say which color car you would like:");
    carApp.carColour = carChooser.nextLine();
    System.out.println("Which features would you like added to your car:");
    carApp.features = carChooser.nextLine();
    carApp.carFinal();

}
}

The system doesn't seem to print the price? So I always get the following:

Your car will be delivered to you in 7 working days. At a price of R0.

Any help would be greatly appreciated, I'm sure it's something quite trivial, maybe something I've overlooked. Thanks in advance,

Fred

Fred
  • 35
  • 1
  • 5
  • 1
    @RohitJain At this point, I think that ~10% of all first questions with a Java tag involve incorrectly comparing Strings. We need a public service announcement. – Kon Aug 26 '13 at 18:43

1 Answers1

4

When comparing Strings you should use .equals.

For example:

if(carMake.equals("ford"))
{
    carPrice = 120000;
}
else if(carMake.equals("porsche"))
{
    carPrice = 1000000;
}

Two additional notes:

  1. For this use case, you may wish to use .equalsIgnoreCase, which checks for equality, ignoring the case. For example, this would trigger the first case regardless of whether the user has entered "ford", "Ford", "FORD", "fOrD", etc.
  2. Some developers prefer using the Yoda Conditions convention, which results in conditionals being written like if ("ford".equals(carMake)). When used with instance methods such as .equals, it can prevent subtle NullPointerExceptions from leaking into your code. When used with the == operator, it can prevent accidental assignments.
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
  • Thank you Jonathan. Coming from scripting languages, this was kind of weird. Makes sense now. – Fred Aug 28 '13 at 17:28