- #1
- 84
- 0
Homework Statement
Write a method isPalindrome that accepts a string as argument and returns true or false
indicating if the string is a palindrome or not. A palindrome is string that can be read the same way forward and backward. Your method must handle upper and lower case characters (the string “Madam” is a palindrome).
You are not allowed to generate a new string in the your implementation of this method. Rather, you should walk through the string to determine if is a palindrome or not.
Use this method to write a program Palindromes that takes an integer command line argument N followed by N strings and prints the strings that are palindromes.
Homework Equations
The Attempt at a Solution
Code:
public class Palindromes
{
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
boolean result;
String str = "";
for (int i = 1; i <= N; i++)
{
str = args[i];
result = isPalindrome(str);
if (result)
System.out.println(str + " is a palindrome.");
else
System.out.println(str + " is not a palindrome.");
}
}
public static boolean isPalindrome(String str)
{
if (str.length() <= 1)
return true;
char right, left;
char c = ' ';
char d = ' ';
int first = 0;
int last = str.length() - 1;
while (c != d)
{
c = str.charAt(first);
right = Character.toLowerCase(c);
d = str.charAt(last);
left = Character.toLowerCase(d);
if (c == d)
{
first++;
last--;
}
else
return false;
}
return true;
}
}
I having trouble figuring out the boolean expression after the while statement. I did most of the code, and hopefully most of it is okay, so any help is appreciated.