Reputation: 2120
I am learning java step by step:
I have a practice problem problem statement link and this is my code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int test, numProcess = 0;
boolean checkString ;
String alpha = "abcdefghijklmnopqrstuvwxyz";
Scanner sc = new Scanner(System.in);
test = sc.nextInt();
for (int i = 0; i < test; i++) {
String original = sc.nextLine();
checkString = checkPalindrome(original);
while (!checkString) {
char oldchar = original.charAt((original.length() - 1));
char newchar = alpha.charAt((original.indexOf(oldchar) - 2));
original = original.substring(0, original.length()-1)+ newchar;
checkString = checkPalindrome(original);
numProcess++;
}
System.out.println(numProcess);
}
sc.close();
}
public static boolean checkPalindrome(String original) {
String newString = "";
for (int i = (original.length() - 1); i >= 0; i--) {
newString += original.charAt(i);
}
return (newString.equals(original));
}
}
the problem is when we try as input,
"abc"
as string(IN WHILE LOOP) 1st iteration makes original = abb
then goes to function which returns false(that is right) Upvotes: 0
Views: 125
Reputation: 2120
I have figured out what was the real problem .. when reading string through scanner like as an example in the format testcase(how many int) and string(check for this string solution) -> 1 abc .. the string will be readed as " abc" and not "abc" which is the error i made in accepting string as input by making sc.nextLine(); which should be used as sc.next(); so checkPalindrome was always returning false ... hushhhhh!!! at last got the solution..
Vote up if I am right
Upvotes: 0
Reputation: 35557
First of all, If you put input as abc
. Your code will throws an Exception
Scanner sc = new Scanner(System.in);
test = sc.nextInt(); // reading an int
While you are putting abc
.
You are trying to find whether given String is palindrome, You can do it as following way easily.
public static boolean isPalindrome(String original) {
StringBuilder sbOriginal = new StringBuilder();
sbOriginal.append(original);
StringBuilder sbReverse=sbOriginal.reverse();
return sbOriginal.toString().equals(sbReverse.toString());
}
Upvotes: 1
Reputation: 1398
for (int i = (original.length() - 1); i > 0; i--)
Your new string doesn't contains first character: the "abc" string will become to "cb". You should change your for condition to i >= 0
or i > -1
Upvotes: 0