views:

163

answers:

3

I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `public class Palindrome {

public static void main(String args[]) {  
  String s="";  
  int i;  
  int n=s.length(); 
  String str="";  

  for(i=n-1;i>=0;i--)  
   str=str+s.charAt(i);  

  if(str.equals(s))  
   System.out.println(s+ " is a palindrome");  

  else  System.out.println(s+ " is not a palindrome"); }

}
+4  A: 

To read in the text, you'll need to make use of the Scanner class, for example:

import java.util.*;

public class MyConsoleInput {

    public static void main(String[] args) {
        String myInput;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter some data: ");
        myInput = in.nextLine();
        in.close();

        System.out.println("You entered: " + myInput);
    }
}

Apply this concept before you actually do a palindrome check, and you're sorted on that front.

As for looping over to allow multiple checks, you can do something like provide a keyword (such as "exit") and then do something like:

do {
    //...
} while (!myInput.equals("exit"));

With your relevant code in the middle, obviously.

James Burgess
myInput!="exit" -- should use `!s1.equals(s2)`; `s1 != s2` won't work.
polygenelubricants
Whoops - thanks for pointing it out!
James Burgess
A: 

Another common idiom is to wrap your test in a method:

private static boolean isPalindrome(String s) {
    ...
    return str.equals(s);
}

Then filter standard input, calling isPalindrome() for each line:

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = in.readLine()) != null) {
        System.out.println(isPalindrome(s) + ": " + s );
    }
}

This makes it easy to check a single line:

echo "madamimadam" | java MyClass

or a whole file:

java MyClass < /usr/share/dict/words
trashgod
+1  A: 

Not a real answer since it's already given (hence CW), but I couldn't resist (re)writing the isPalindrome() method ;)

public static boolean isPalindrome(String s) {
    return new StringBuilder(s).reverse().toString().equals(s);
}
BalusC
Yes, but presumably this is homework, and they'd be forbidden from doing something like that.
polygenelubricants
Ach, it's Friday.
BalusC