[英]Is there some kind of “and” statement in Java?
I have a question which I would like to be answered. 我有一个想回答的问题。 I am in the making of a app which needs to use booleans. 我正在制作一个需要使用布尔值的应用程序。 This is my code so far 到目前为止,这是我的代码
if (but1 = true){
//Do Something
}
But I would like to use a some type of and
function in so I can say something like 但是我想在其中使用某种类型的and
函数,这样我可以说
if (but1 = true and but2 = true){
//Do Something
}
I have declared all my Boolean variables and would like to know if there is any type of function which will allow me to support this type of code which I need. 我已经声明了所有布尔变量,并想知道是否有任何类型的函数可以支持我需要的这种类型的代码。 Thanks 谢谢
This is : 这是 :
if (but1 && but2){
//Do Something
}
Just simple Java. 只是简单的Java。
I think that should be written this way: 我认为应该这样写:
if (but1) {
//Do Something
}
if (but1 && but2){
//Do Something
}
Logical and is &
. 逻辑与是&
。 &&
will shortcut the evaluation if the first parameter is false. 如果第一个参数为false,则&&
将简化评估。 Example: 例:
// foo() and bar() will be called
if (foo() & bar()) {
}
// bar() will not be called if foo() returns false
if (foo() && bar()) {
}
Ok, this question has been been well answered, but just to make you aware: 好的,已经很好地回答了这个问题,但是只是为了通知您:
if (but1 = true){
//Do Something
}
will always evaluate as true as it takes the new value assigned to but1
由于它将采用分配给but1
的新值,因此将始终为true
Also using the '==' operator is unnecessary for booleans. 对于布尔值,也不需要使用“ ==”运算符。
&& is also a short circuit operator. &&还是短路操作员。 If the first evaluation fails the second is not checked. 如果第一个评估失败,则不检查第二个评估。 You can use one & which check both parts of the statement. 您可以使用&来检查语句的两个部分。
For example 例如
if (a() && b()){...}
Will not evaluate b() if a() is false. 如果a()为假,则不会评估b()。 If you had one & then b() is evaluated even if a() is false 如果您有一个&,则即使a()为false,也将评估b()
This is the same for or (¦ and ¦¦) 或((和¦))相同
You cannot compare variables with =
. 您不能将变量与=
进行比较。 A single equals sign is used for assignment, where ==
is used for comparison. 单个等号用于分配,其中==
用于比较。
In Java, you can do the following: 在Java中,您可以执行以下操作:
if (a == true && b == true)
{
//do code
}
Try this: 尝试这个:
if (but1 == true && but2 == true) {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.