I need to write a program that gets a string from the user and tests to see if it’s a palindrome. This has to be done with nested loops: I can’t write a method to return the answer. I also have to keep accepting string inputs and testing them until the user enters an empty line, at which point the program prints ‘goodbye’ and terminates. What I’m having trouble with is getting the program to accept input after the two possible points of input (is a palindrome, is not), and to then use the new input in the loops, and print the appropriate line each time.
Here’s what the output is supposed to look like:
Enter a string: rotor
rotor is a palindrome.
Enter a string: mummy
mummy is not a palindrome.
Enter a string:
Empty line read. Goodbye.
This is what I have so far, and it tests each input and returns the correct statement, but it does nothing when the input is empty:
System.out.print("Enter a string: ");
String input = in.next();
if (input.length() > 0) {
int x = 0;
int y = input.length()-1;
while (x < y) {
if (input.charAt(x) == input.charAt(y)) {
x++;
y--;
}
else {
System.out.println(input + " is NOT a palindrome.");
System.out.println("Enter a string: ");
input = in.next();
}
System.out.println(input + " is a palindrome.");
System.out.println("Enter a string: ");
input = in.next();
}
}
else {
System.out.print("Empty line read - Goodbye!");
}
Any thoughts? This is homework, btw, so I’m not looking for The Answer so much as clues, or what I need to be looking at.
OK, Since it’s your homework, I’ll just give you a brief description about how you can proceed: –
Since you need to continously take user input, so probably you would be needing some kind of loop, that can continue until a condition is reached (You can think, what loop constrct will go here)
Secondly, you need to ask user when he want to quit, so you need to specify a exit condition..
Third, for checking for palindrome, you need to check a string with it’s reverse..
Since you have to use nested loop, you can use
lengthof the string entered, in your loop condition.. Remember, you just need to loop till half the length. Why, you need to find out.. then, compare first character with last, then 2nd character with 2nd last.. until characters are matching.. You need to find out when you will exit the loop..I think this much information will get you started..
Also one more thing.. May be you are restricted with the use of any method, but it is absolutely bad idea and ugly design to do everything in
main().. In fact any of your method should not do more than one task.. And especially yourmain()method should ideally be just 4 – 5 lines long..When coding a method, if you think this part is something different, move it outside to another method, and invoke it.. This is the way you should code..