Not only decreasing the value of b
, there are several more errors in your code for which it will never be compiled successfully. Actually, the whole code is full of errors. I am pointing out the errors one by one but one suggestion for you, try to learn the fundamentals of JAVA programming properly before getting your hand dirty on actual problem solving.
1.
String reverseString = 0;
You should get compilation error with that line as int cannot be converted to String.
The correct syntax can be like this:
String reverseString = "";
2.
int x = inputString.length;
In Java, length
variable is applicable for arrays whereas, for strings, length()
method do the same.
So, the fix is:
int x = inputString.length();
3.
int b = inputString.length;
As you are fetching charAt(b)
later on your code, you'll get StringIndexOutOfBoundsException
. As indexing in charAt()
starts from 0 and ends at string_length - 1.
So, correction is:
int b = x;
4.
for (int i = 0; i > x; i++)
Completely wrong logic, check at the condition properly. i > x
means the loop will not proceed further at all. So, it should be:
for (int i = 0; i < x; i++)
5.
int b - 1;
Blatantly wrong syntax. If you want to decrement the variable value, you don't need the int
before doing every operation with already declared variable. And so, the correct syntax can be:
b = b - 1;
Or, Simply:
b--;
6.
String reverseString = reverseString + "a";
Once I've told you should use data type for a variable once during declaration. And also "a"
is simply a string here. For getting the variable value, you should have used just a
, not with ""
. So, the fix is:
reverseString = reverseString + a;
7.
if (reverseString == inputString) {
return false;
}
else {
return true;
}
First thing is, we don't compare string equality in java using ==
sign. That is because ==
just compares the object not the actual contents inside the string. In this case, you have to use .equals()
method. Another thing is, as your method name is checkPalindrome()
, ideally it should return true when it is palindrome and false when it is not. But, you are doing it reverse. IDK, may be you are handling this properly as a reverse manner also inside your main()
or from where you are calling this method.
So, the correction will be:
if (reverseString.equals(inputString))
return true;
else
return false;
So, That's all
The full method will be like this:
boolean checkPalindrome(String inputString) {
String reverseString = "";
int x = inputString.length();
int b = x;
for (int i = 0; i < x; i++) {
char a = inputString.charAt(b);
b--;
reverseString = reverseString + a;
}
if (reverseString.equals(inputString))
return true;
else
return false;
}
The code can be further simplified to this:
boolean checkPalindrome(String inputString) {
String reverseString = "";
int x = inputString.length();
for (int i = x - 1; i >= 0; i--)
reverseString += inputString.charAt(i);
if (reverseString.equals(inputString))
return true;
else
return false;
}