So I have my code:
import java.util.Scanner;
public class PalindromeDriver
{
public static void main(String[] args)
{
String another = "y";
Scanner scan = new Scanner(System.in);
PalindromeTester section = new PalindromeTester();
while (another.equalsIgnoreCase("y"))
{
System.out.println("Enter a palindrome:");
String str = scan.nextLine();
if (section.palindromeTest(str))
System.out.println(str + " IS a palindrome!");
else
System.out.println(str + " is NOT a palindrome!");
System.out.println("Test another?(y/n)");
another = scan.nextLine();
}
}
}
and... import java.util.*;
public class PalindromeTester
{
public boolean palindromeTest(String str)
{
if (str.length() <= 1)
return true;
if (str.charAt(0) == str.charAt(str.length() - 1))
return palindromeTest(str.substring(1, str.length() - 1));
return false;
}
}
I was told that my code is good, but that i should have some more methods added into PalindromeTester, such as a constructor and a method that would store a potential palindrome into an instance variable, what would adding these methods do for my program if it already runs correctly?
For now, your PalindromeTester is a simple Utility class - it checks one string to be a palindrome or not. So one might argue if it's even worth putting that into a class - you could have that method in PalindromeDriver over all.
Let's for a second look at the suggestions:
Have a constructor. Use an instance variable
public class PalindromeTester {
private String palindrome;
public PalindromeTester(String candidate) {
palindrome = candidate;
}
}
Given this class, you could then convert your utility call palindromeTest
into a slightly more appealing form:
public boolean isPalindrome() {
//Do check here
}
And then think about additional methods like
public String getForwards() {
//
}
public String getBackwards() {
//
}
All without the need to pass that string in once more.
Bottomline
What it would buy you? It would make your program more "Object oriented" and less "functional". And better to read maybe. And more extensible for the future.