Tuesday, July 15, 2014

Lexicographical Order

Exercise 2.12  Write a program that reads two strings from the keyboard and prints the largest
(relative to lexicographical order). Use the compareTo method to compare the strings.

import java.util.*;

public class Lexicographical {
public static void main(String[] args) {
System.out.print("First string: ");
Scanner input = new Scanner(System.in);
String x = input.next();
System.out.print("Second string: ");
String y = input.next();
int i = x.compareTo(y);
input.close();
if (i<0){
System.out.print("The larger string is: "+y);
}
else if (i>0){
System.out.print("The larger string is: "+x);
}
else
{
System.out.print("The strings are equal.");
}
}
}

No comments:

Post a Comment