import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean x;
Scanner sc = new Scanner(System.in);
String igual = sc.next().toString();
String[] yes = new String[15];
yes[0]="When I find myself in times of trouble";
yes[1]="Mother Mary comes to me";
yes[2]="Speaking words of wisdom";
yes[3]="Let it be ";
yes[4]="And in my hour of darkness ";
yes[5]="She is standing right it front of me ";
yes[6]="mama just killed a man";
yes[7]="And when the broken hearted people ";
yes[8]="Living in the world agree ";
yes[9]="There will be an answer ";
yes[10]="For though they may be parted";
yes[11]="there is still a chance that they will see";
yes[12]="And when the night is cloudy";
yes[13]="There is still a light that shines on me";
yes[14]="Shine until tomorrow";
String[] no = new String[5];
no[0]="I wake up to the sound of music";
no[1]="Mother Mary comes to me";
no[2]="put a gun against his head";
no[3]="pulled my trigger now his dead";
no[4]="mama life had just began";
// searches in the yes array
for (int i=0 ; i<yes.length ; i++){
x=igual.trim().equalsIgnoreCase(yes[i].trim());
if (x=true){
System.out.println("true");
}
}
//searches in the no array
for (int j=0 ; j<no.length ; j++){
x = igual.trim().equalsIgnoreCase(no[j].trim());
if (x=true){
System.out.println("false");
}
}
}
}
打印15次真实 5次假 即使您输入的字符串只等于数组中的一个字符串。 我对代码进行了验证,结果就是这些 看起来它在'if'条件中设置'x'变量 先感谢您。
答案 0 :(得分:7)
作业将返回右侧。因此(来自您的if
- 声明条件):
x=true
始终返回true
。您可能正在寻找x == true
或更常规的x
(如if (x) {...}
所示)。通常应该更倾向于更简单的第二种变体。
答案 1 :(得分:3)
使用x == true
,一个等式表达式,而不是x = true
,这是一个赋值表达式。
JLS chapter 15.26说这个
在运行时,赋值表达式的结果是值 分配发生后的变量。
所以,在代码中
if (x = true)
x
被分配true
,然后if
评估true
。因此,无论您从equalsIgnoreCase
获得什么值,语句都将始终进入if
块,因为赋值表达式将返回true
。
此外,您不需要对布尔值进行条件检查。你可以简单地使用
if (x) { // read as if x is true
...
}