注:这篇博文当时写的时候有点问题,今天(2020-02-13)已修正。但是文章摘要还是修改前的内容,特此说明。
代码如下:
import java.util.Scanner;
/**Java how to program, 10th edition
* 14.3 (Comparing Strings) Write an application that uses String method compareTo
* to compare two strings input by the user. Output whether the first string is
* less than, equal to or greater than the second.
* @author [email protected]*/
public class CompareTo
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("请输入字符串1:");
String s1=input.nextLine();
System.out.print("请输入字符串2:");
String s2=input.nextLine();
int result=s1.compareTo(s2);
if (result>0)
System.out.printf("字符串1-%s大于字符串2-%s%n",s1,s2);
else if (result<0)
System.out.printf("字符串1-%s小于字符串2-%s%n",s1,s2);
else
System.out.printf("比较结果:字符串1-%s等于字符串2-%s%n",s1,s2);
}
}
运行结果:
请输入字符串1:海
请输入字符串2:斌
字符串1-海大于字符串2-斌
附:
JavaDoc中对compareTo方法的说明如下:
int java.lang.String.compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by thisString
object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if thisString
object lexicographically precedes the argument string. The result is a positive integer if thisString
object lexicographically follows the argument string. The result is zero if the strings are equal;compareTo
returns 0
exactly when the equals(Object)
method would returntrue
.
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at positionk has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case,compareTo
returns the difference of the two character values at positionk
in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case,compareTo
returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()
Parameters:
anotherString the String
to be compared.
Returns:
the value 0
if the argument string is equal to this string; a value less than0
if this string is lexicographically less than the string argument; and a value greater than0
if this string is lexicographically greater than the string argument.