Reputation: 11
I have started to learn java and I've run into some trouble. Just wondering why my compare string function is not working and always returning true;
The purpose of the program is to take an input of a string, reverse the string and see if the string is the same as the original input (palindrome).
import java.util.Scanner;
public class palinedromeString {
private static Scanner keyboard;
public static void main(String[] args) {
System.out.println("Please enter a Palindrome");
keyboard = new Scanner(System.in);
String input = keyboard.next();
String original = input;
System.out.println("You entered: " + original);
System.out.println("Your String reversed is:" + " " + stringReverse(input));
System.out.println(checkString(input, original));
}
public static String stringReverse(String a) {
String result = "";
for(int i = a.length()-1; i>=0; i--){
result = result + a.charAt(i);
}
return result;
}
public static boolean checkString(String a, String b){
if(b.equals(a)){
return true;
}
else{
return false;
}
}
}
Upvotes: 1
Views: 7993
Reputation: 1
Here in checkString(input, original)
method, both the parameter has same value, Hence it always returns true.
You have to pass original and reversed string like this:
String reversedStr = stringReverse(input);
checkString(reversedStr , original);
Upvotes: 0
Reputation: 543
You have different options.
Assign the
stringReverse(input)
to a variable like
input=stringReverse(input);
before checking
The thing is you are reversing the string into a different variable and it doesnot get reflected in the String you pass unless you explicitly assign it.
Upvotes: 0
Reputation: 3570
Because you are passing input and original to the checkString() method. those two hold the same values. It's obvious you get true always.
checkString(stringReverse(input), original);
You have to use the above instead.
Upvotes: 1
Reputation: 201437
stringReverse
returns the reversed String
(it doesn't operate in place). Update input
and your code should work as expected. Something like,
input = stringReverse(input);
System.out.println("Your String reversed is:" + " " + input);
Also, checkString
is equivalent to
return b.equals(a);
Upvotes: 1