User question
My program checks to see if a word or phrase is a palindrome (reads the same in both the reverse and the front, former "race car"). The problem I'm running into is that someone walks into a "race car" to actually get it. In the code below I have indicated where if I type in "race car" and run Java returns the correct answer, so I know I am here. But what am I missing to get into the console. I think my code is ok, but maybe I am missing something or in the wrong place? Actually, I am not looking for a new answer unless I miss something, but if possible, perhaps, this moves my code into the correct scope bc. I am 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 am new to programming, so I hope I succeed. I know palindrome check works. I just need help testing where I enter the console. Thanks to
a source to share
Everything looks fine, but the loop for
shows that you are checking to see if it is a s
palindrome, not myInput
.
Now all you have to do is replace all occurrences s
with myInput
and then check if your program is working correctly.
As a heads-up, your program does not recognize the phrase "Madam Im Adam" as a palindrome.
Since this is homework, one possible approach to recognizing phrases (without changing the code) is to remove spaces (you can use String#replaceAll
) from your string and then do a palindrome check.
a source to share
First of all, the code you provided will not compile; that aside. It looks like you are looking for how to "read user input"
Here's what you need to do in simple words:
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 continue your code to test the "s" for paliandrome.
a source to share