我不太擅长编程,也不知道为什么这不起作用。无论我输入什么,它总是直接进入else语句。
public void pizzaIntro()
{
Scanner user_input = new Scanner(System.in);
String user_command = "null";
String apology = "I'm sorry it appears there has been some kind of mistake in your order.";
System.out.println("Welcome to " + cM + " here we strive to deliver excellent services to all our customers!");
System.out.println("The current prize for pizza is $" + bP + " and an extra $" + tP + " per topping.");
System.out.println(); System.out.println();
while(user_command != "exit")
{
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if(user_command.toLowerCase() == "yes")
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.toLowerCase() == "no")
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
pic1.show();
}
答案 0 :(得分:2)
使用equals方法比较字符串。要了解==和equals之间的区别,请阅读https://stackoverflow.com/questions/7311451/difference-between-equals-and-instanceof 您将清楚地知道何时使用。
while(!(user_command.equals("exit")) {
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if(user_command.toLowerCase().equals("yes"))
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.toLowerCase().equals("no"))
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
答案 1 :(得分:1)
使用equals
方法代替==
user_command.toLowerCase().equals("yes")
在Java中,==总是只比较两个引用。可以将它用于原始数据类型。 String不是原始数据类型。 String是一个对象。你应该使用equals方法。
在您的情况下,您可以考虑使用equalsIgnoreCase
方法忽略案例。
答案 2 :(得分:1)
使用equalsIgnoreCase
。它更安全
public void pizzaIntro()
{
Scanner user_input = new Scanner(System.in);
String user_command = "null";
String apology = "I'm sorry it appears there has been some kind of mistake in your order.";
System.out.println("Welcome to " + cM
+ " here we strive to deliver excellent services to all our customers!");
System.out.println("The current prize for pizza is $" + bP
+ " and an extra $" + tP + " per topping.");
System.out.println();
System.out.println();
while (!user_command.equalsIgnoreCase("exit"))
{
System.out.print("Would you like toppings?(yes/no):");
user_command = user_input.next();
if (user_command.equalsIgnoreCase("yes"))
{
System.out.println("Good Eat Your Pizza.");
}
else if (user_command.equalsIgnoreCase("no"))
{
System.out.println("Well Ok Then!");
}
else
{
System.out.println(apology);
System.exit(1);
}
}
pic1.show();
}
答案 3 :(得分:1)
永远不要将任何Java对象与“==”进行比较(只有原语如int,long,double等)。它应该是:
if(user_command.toLowerCase().equals("yes")) {
...
}
否则你检查对象的位置是否相同,而不是内容。
在这个特定示例中,您可能只想使用String.equalsIgnoreCase(...)。