This question already has answers here:
How do I compare strings in Java?
                                
                                    (23个答案)
                                
                        
                                6年前关闭。
            
                    
我正在学习Java,并且正在努力了解为什么我编写的一个简单程序未按应有的方式工作。

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();

}
}


系统似乎没有打印价格?所以我总是得到以下内容:

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


任何帮助将不胜感激,我敢肯定这是一件微不足道的事情,也许是我忽略的事情。提前致谢,

弗雷德

最佳答案

比较字符串时,应使用.equals

例如:

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




另外两个注意事项:


对于此用例,您可能希望使用.equalsIgnoreCase,它会检查是否相等,而忽略大小写。例如,这将触发第一种情况,而不管用户是否输入了“ ford”,“ Ford”,“ FORD”,“ fOrD”等。
一些开发人员更喜欢使用Yoda Conditions约定,这导致条件的编写类似于if ("ford".equals(carMake))。与.equals等实例方法一起使用时,它可以防止细微的NullPointerExceptions泄漏到您的代码中。与==运算符一起使用时,可以防止意外分配。

10-07 12:09