Friday, February 27, 2009

Java Problem 21

The next problem I tried to solved was problem 21.


/*
* 21. Write a Java class called Equals, which defines a
* main() method that asks the user to enter two Strings s1
* and s2, and displays whether or not s1 and s2 are equal.
* Two Strings are equal if they are of the same length
* and the same characters appear in the same positions.
* You MUST NOT use any of the methods defined in the String
* class other than charAt() and length().
*
* @author obispo
*/

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

s1 = JOptionPane.showInputDialog(null, "Enter first string:");
s2 = JOptionPane.showInputDialog(null, "Enter second string:");

len = s1.length();
if (len != s2.length()) {
result = -1;
} else {
for (index = 0; index < len; index++) {
if (s1.charAt(index) != s2.charAt(index)) {
result = -1;
}
}
}

if (result == 0) {
JOptionPane.showMessageDialog(null, "Equal !\n" +
s1 + " == " + s2);
} else {
JOptionPane.showMessageDialog(null, "Not Equal !\n" +
s1 + " != " + s2);
}
}
}

No comments: