[英]Using “OR” operator in Java
这是代码。
do {
System.out.println("Enter Product Code: ");
medicine = machine1.nextInt();
if (medicine==1) {
machine1.buy1();
machine1.addproduct();
}
if (medicine==2); {
machine1.buy2();
machine1.addproduct();
}
} while((String answer=='y') || (String answer=='Y'));
它给出了这个错误:
enter code drugstore1.java:96: error: ')' expected }while((String answer=='y'))||((String answer=='Y')); ^ drugstore1.java:96: error: ';' expected }while((String answer=='y'))||((String answer=='Y')); ^ drugstore1.java:96: error: ';' expected }while((String answer=='y'))||((String answer=='Y')); ^
修正其他错误后,它发出欺骗声。 我认为我使用的是正确的。
我建议你写
while(answer.equalsIgnoreCase("y"));
的
while((String answer=='y'))||((String answer=='Y'));
您不能在逻辑条件内定义新变量。
1. String answer [X] -> answer [V]
2. answer=='y' [X] -> answer.equals("y") [V]
3. answer.equals("y") || answer.equals("Y") [V] -> answer.equalsIgnoreCase("y") [V]
4. if(medicine==2); [X] -> if (medicine == 2) [V]
尝试在所有人同时使用double quote
和equalsignorecase
方法的情况下,如下所示:
while(answer.equalsignorecase("y"));
要在创建变量时插入字符串“ y”,请尝试使用nextLine()
:
String answer= machine1.nextLine();
像这样:
System.out.println("Enter Product Code: ");
medicine = machine1.nextInt();
System.out.println("Enter y if you want leave: ");
String answer= machine1.nextLine();
以下是一些准则:
不要在while()语句中声明对象 。 您是说while(answer=="y")
吗?
不要使用==运算符比较字符串 。 字符串与.equals()
进行比较。 ==
仅检查两个操作数是否在相同的物理内存位置。
您正在尝试在条件内声明变量:
String answer=='y'
变量声明如何用作比较?
应该在哪里answer
可以是从哪里来的? 它在您的代码中不存在,因此根本不清楚您要在其中完成什么。
但是,一旦您的代码中确实有一个answer
变量,该变量可能包含一些'y'
或'Y'
值,就可以像这样进行比较:
while(answer.equalsIgnoreCase("y"))
此外,您在这里还有一个错误:
if(medicine==2);
该分号将静默终止if
块,并且无论条件如何,下一个代码块将始终执行。 删除该分号。
它应该是
while("y".equalsIgnoreCase(answer)){// will avoid null pointer exception if answer is null
if(medicine==1)
{
machine1.buy1();
machine1.addproduct();
}
else if(medicine==2) // better for performance as both if conditions are mutually exclusive
{
machine1.buy2();
machine1.addproduct();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.