Boolean始终输出true

use*_*571 0 java loops if-statement boolean

我有一堂课来测试回文.在我的循环中,它比较每个字母以查看它们是否匹配,如果它们不匹配,则应该将布尔变量设为false,反之亦然.现在我已经测试了一下,我可以看到,如果我正确地放入回文,它实际上会转到正确的if语句,这使得变量为true.如果它遇到一对不匹配的字母,它应该将布尔变量声明为false并从循环中断,它实际上正确地执行.但无论如何,当我尝试使用它来确定响应回来时,布尔变量总是为真,我不知道为什么.

 is a palindrome!  Hooray!
Run Code Online (Sandbox Code Playgroud)

总是输出,即使循环转到假布尔并打破,它让我感到困惑.

public class Palindrome
{
public static void main(String[] args) 
{
    //is it true?
    boolean truth;
    //create stack and queue
    Stack s = new Stack();
    Queue q = new LinkedList();
    //scanner
    Scanner input = new Scanner(System.in);
    //get string
    System.out.println("Enter a palindrome, or don't, I'll know:");
    String palin = input.nextLine();
    //remove whitespace
    palin = palin.replaceAll("\\s+","");
    System.out.println(palin);
    //remove puncuation
    palin = palin.replaceAll("\\p{P}", "");
    System.out.println(palin);
    //set lowercase
    palin = palin.toLowerCase();
    System.out.println(palin);

    //feed string to stack and queue
    for(int i = 0; i < palin.length(); i++)
    {
        s.push(palin.charAt(i));
        q.add(palin.charAt(i));
    }
    System.out.println(s);
    System.out.println(q);
    while(!s.isEmpty() && !q.isEmpty())
    {
        Object sTemp = s.pop();
        Object qTemp = q.poll();
        String sString = sTemp.toString();
        String qString = qTemp.toString();
        System.out.println(sString + qString);
        System.out.println("looptest");
        if(sString.equals(qString))
        {
            truth = true;
        }
        else
        {
            truth = false;
            break;
        }
    }
    if(truth = true)
    {
        System.out.println(palin + " is a palindrome!  Hooray!");
    }
    else
    {
        System.out.println(palin + " is no palindrome! You lied!");
    }
}
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 7

有了这条线

if(truth = true)
Run Code Online (Sandbox Code Playgroud)

要分配truetruth=,当你可能是指==比较.它已经是一个boolean,所以只需要它作为条件.

if (truth)
Run Code Online (Sandbox Code Playgroud)