views:

71

answers:

2

My program checks to test if a word or phrase is a palindrome (reads the same both backward and forward, ex "racecar"). The issue I'm having is after someone enters in "racecar" getting it to actually test. In the below code, I marked where if I type in "racecar" and run, Java returns the correct answer so I know I'm right there. But what am I missing as far as entering it into the console. I think my code is ok, but maybe I have something missing or in the wrong spot? Not really looking for a new answer unless I'm missing something, but if possible perhaps a pro at this moving my code to the correct area bc I'm stuck!

import java.util.*; 

public class Palindrome { 

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

    System.out.println("Enter a word or phrase: ");  **//this asks user for input but doesn't check for whether or not it is a palindrome**
    myInput = in.nextLine(); 
    in.close(); 

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

{
    String s="racecar";  **//I can type a word here and it works but I need**
    int i;               **//I need it to work where I ask for the input** 
    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"); }

}

I'm new at programming so I'm hoping what I got is ok. I know the palindrome test works I'm just needing helping having it test thru where I'm entering it into the console. Thanks

+1  A: 

Everything looks okay, however your for loop still shows you are checking to see if s is a palindrome, not myInput.

Now, all you need to do is replace every occurrence of s with myInput and then check to see if your program works correctly.

As a heads up, your program will not recognize the phrase "Madam Im Adam" as a palindrome.

Since this is homework, one possible approach to recognize phrases (without altering your code) is to remove spaces (you could use String#replaceAll) in your string and then perform the palindrome check.

Anthony Forloney
+1  A: 

First of all, the code you have given will not compile; that aside. Looks like what you are looking for is to "how to read user input"

Here is what you need to do in simple terms:

import java.util.Scanner;
...
...

Scanner in = new Scanner(System.in);

// Reads a single line from the console 
// and stores into variable called "s"
String s= in.nextLine();
in.close();

Then proceed with your code for checking "s" for paliandrome.

ring bearer
if you just need to read a single line, a scanner is overkill...Using a BufferedReader should be less resource-consuming.
Valentin Rocher