In Java Weird Al Yankovic’s song “Bob” is a satiric homage to Bob Dylan. Here ar
ID: 3837347 • Letter: I
Question
In Java
Weird Al Yankovic’s song “Bob” is a satiric homage to Bob Dylan. Here are the fi rst few lines:
I, man, am regal - a German am I
Never odd or even If I had a hi-fi
Madam, I’m Adam
Too hot to hoot
No lemons, no melon
Too bad I hid a boot
Lisa Bonet ate no basil
Warsaw was raw
Was it a car or a cat I saw?
If you ignore case and punctuation, you will notice that every line of the song (and the title too) reads the same backwards and forwards. Such lines are called palindromes . Write a program that accepts a string and determines whether or not the string is a palindrome. Ignore all whitespace and punctuation, and assume that there is no distinction between upper- and lowercase letters. For example, “a man, a plan, a canal, Panama”, and “a Toyota’s a Toyota” are palindromes, but “Babel” is not.
Explanation / Answer
public class Palindrome {
public static boolean isPlaindorme(String s)
{
s = s.toLowerCase().replaceAll("\W", "");
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
if(isPlaindorme("I, man, am regal - a German am I"))
{
System.out.println("'I, man, am regal - a German am I' is palindrome." );
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.