In: Computer Science
Can someone look into my code and tell me what do you think: Thats Palindrome;
//class name Palindrome
public class Palindrome {
public static void palindromeChecker(String... str)
{
// takes string one by one
for (String s : str) {
// creates a
stringbuilder for s
StringBuilder sb
= new StringBuilder(s);
// reverses the
sb
sb.reverse();
// checks if
both are equal
if
(s.equals(sb.toString())) {
System.out.println(s + " is Palindrome");
} else {
System.out.println(s + " is not a
Palindrome");
}
}
}
}
//Testing Palindrome
public class TestPalindrome {
public static void main(String[] args) {
Palindrome pal = new
Palindrome();
//Checking palindrome
pal.palindromeChecker(" ", "a",
"aa", "bb", "aba", "bab", "bob", "ab", "ba", "bba", "abb");
}
}
The given code is correct according to logic. Only one thing is not standard is that inside main function there is no need to created object of Palindrome class.
Please find the updated code below:
class Palindrome {
public static void palindromeChecker(String... str) {
// takes string one by one
for (String s : str) {
// creates a stringbuilder for s
StringBuilder sb = new StringBuilder(s);
// reverses the sb
sb.reverse();
// checks if both are equal
if (s.equals(sb.toString())) {
System.out.println(s + " is Palindrome");
} else {
System.out.println(s + " is not a Palindrome");
}
}
}
}
//Testing Palindrome
public class TestPalindrome {
public static void main(String[] args) {
/*here no need to create object of palindrome checker.
Function can be called directly
as it is static function*/
Palindrome.palindromeChecker(" ", "a", "aa", "bb", "aba", "bab",
"bob", "ab", "ba", "bba", "abb");
}
}
output: