Friday, February 27, 2009

Java Problem 19

Here is the solution for Problem number 19.

/*
* 19. Write a Java class called IsPalindrome, which
* defines a main() method that asks the user to enter
* a String s, and displays whether or not s is a
* palindrome. A palindrome is a String which reads the
* same forwards and backwards, such as "laval" or
* "stressed desserts".
*
* Code taken from my previous solution of problem #21
*
* @author obispo
*/

import javax.swing.*;
import java.text.*;
class IsPalindrome {
public static void main( String[] args ) {
String s1, s2;
int result = 0, len, index1, index2;

s1 = JOptionPane.showInputDialog(null, "Enter a string:");

for (index1 = 0, index2 = s1.length() - 1; index1 < index2; index1++, index2--) {
if (s1.charAt(index1) != s1.charAt(index2)) {
result = -1;
break;
}
}

if (result == 0) {
JOptionPane.showMessageDialog(null, "Palindrome !");
} else {
JOptionPane.showMessageDialog(null, "Not Palindrome !");
}
}
}

No comments: