340,548 views
16 votes
16 votes
Please Help! (Language= Java) Beginners Comp. Science

Assignment Details=

Create a class called Palindromes, which will determine if a user’s entry is a palindrome. A
palindrome is a word or phrase that reads the same backwards or forwards. See the examples.
A Santa at NASA My gym taco cat kayak NOW I WON race car
Your program will ignore spaces and ignore case when determining if a string is a palindrome.
Use the String method replace to remove the spaces. If it is a palindrome, output
PALINDROME, or else output NOT PALINDROME.
Additional requirements:
 Add an infinite loop with a sentinel-trigger break test (allowing them to input multiple
attempts). You may decide on its command word or exit-condition.
 As below, make sure a spacer line exists between each run of the program
Here are two sample runs of the program.
Enter a word or phrase: Noon
PALINDROME
Enter a word or phrase: bookkeeper
NOT PALINDROME

User Iamyojimbo
by
3.1k points

1 Answer

11 votes
11 votes

Answer:

import java.util.Scanner;

class Main {

public static void main(String[] args) {

test("A Santa at NASA");

test("My gym");

test("taco cat");

test("kayak");

test("NOW I WON");

test("race car");

test("bookkeeper");

Scanner scanner = new Scanner(System.in);

while(true) {

System.out.print("Enter a word or phrase: ");

String line = scanner.nextLine();

if (line.equals("exit")) break;

if (Palindromes.isPalindrome(line)) {

System.out.println("PALINDROME");

} else {

System.out.println("NOT PALINDROME");

}

}

scanner.close();

}

public static void test(String s) {

System.out.printf("'%s' is %sa palindrome\\", s, Palindromes.isPalindrome(s) ? "" : "not ");

}

}

class Palindromes {

static boolean isPalindrome(String s) {

s = s.replaceAll("\\s","").toLowerCase();

return s.equals(reverseString(s));

}

public static String reverseString(String str){

StringBuilder sb = new StringBuilder(str);

sb.reverse();

return sb.toString();

}

}

Step-by-step explanation:

I chose to use a string reverse routine. This is slightly less efficient than iterating the string from both ends, but performance is less important than readability here.

The stop word is exit.

User Vishalkin
by
2.3k points