You are on page 1of 1

// CS1020 (AY2014/5 Semester 2)

// Take-home Lab1 Ex2


// Name: Yong Jun Cong
// Matric. No.: **Zap**
// Lab group: 2
// Check if a sentence is a palindrome and determine the number of palindromes g
iven by user
import java.util.* ;
public class Palindromes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numPalindromes = 0;
String str ; // shift this into the while loop, as you are not intendin
g to use str outside of the loop.
System.out.print("Enter text: ");
while (sc.hasNextLine()) {
str = sc.nextLine();
if (isPalindrome(str))
numPalindromes ++;
System.out.print("Enter text: ");
}
sc.close(); // good habit, though not taught in this module =)
System.out.println("Number of palindromes = " + numPalindromes);
}
//check if the sentence is a Palindrome
// -2 from programming style: missing precondition (what if str == null?)
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
// good solution that passes through the entire String only once! =)
while (left<right) {
if (!Character.isLetter(str.charAt(left)))
left ++ ;
else if (!Character.isLetter(str.charAt(right)))
right --;
else if (Character.toLowerCase(str.charAt(left)) != Character.toLowe
rCase(str.charAt(right)))
return false;
else {
left ++;
right --;
}
}
return true;
}
}