Reputation: 1471
I have a class to test a palindrome. In my loop, it compares each letter to see if they match, if they don't, it's supposed to make the boolean variable as false, or vice versa. Now I've tested it a ton, and I can see that if I correctly put in a palindrome, it actually goes to the correct if statement which makes the variable true. If it comes across a pair of letters which don't match, it's supposed to declare the boolean variable as false and break from the loop, which it actually does properly. But no matter what, the boolean variable is always true when I try to use it to determine what response comes back, and I have no idea why.
is a palindrome! Hooray!
is ALWAYS the output, even if the loop goes to the false boolean and breaks, and it baffles me.
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!");
}
}
}
Upvotes: 0
Views: 274
Reputation: 2530
basic ,but most programmer(beginner) tend to typo-error or just dont know the difference of
=
and ==
or meet them officially, so here it goes
=
is assignment operator and
==
test for equality or conditional operator
so in your line
if(truth = true)
{
...
}
you are assigning your variable truth
to have true
as value
Gotta use the ==
so value of your boolean wont change.
if(truth == true)
{
...
}
or
if(truth.equals(true))
{
...
}
Upvotes: -1
Reputation: 178253
With this line
if(truth = true)
You are assigning true
to truth
with =
, when you probably meant ==
to compare. It's already a boolean
, so just have it as the condition.
if (truth)
Upvotes: 7