1
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”变量,提前谢谢你。

4

2 回答 2

7

作业返回它们的右手边。因此(根据您的if-statement 条件):

x=true

总是返回true。您可能正在寻找,x == true或者更传统地,x(如if (x) {...})。更简单的第二种变体通常应该受到青睐。

于 2013-07-24T21:21:45.883 回答
3

使用x == true,一个相等表达式,而不是x = true,它是一个赋值表达式。

JLS,第 15.26 章,这样说

在运行时,赋值表达式的结果是赋值发生后变量的值。

所以,在代码中

if (x = true)

x被分配true,然后if评估它true。因此,无论您从 中获得什么值equalsIgnoreCase,语句都将始终进入if块,因为赋值表达式将返回true

此外,您不需要对布尔值进行条件检查。你可以简单地使用

if (x) { // read as if x is true
    ...
}
于 2013-07-24T21:20:32.000 回答