【发布时间】:2022-11-22 06:42:42
【问题描述】:
所以我这里有一些代码。它的目的是比较用户输入的 2 个字符串,它应该输出第一个字符串是 > < 还是 = 第二个字符串。
它在大多数情况下都有效,除了当我输入两个短语如 gh 和 hi 时,它认为 gh 大于 hi。也许它正在查看实际字母的大小。我不确定。
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first phrase(s): ");
String one = scanner.next();
System.out.print("Enter Second phrase(s): ");
String two = scanner.next();
int length = one.compareTo(two);
if(length > 0){
System.out.print("String one is less than string two.");
}else if (length < 0) System.out.print("String one is greater than string two.");
else
System.out.print("Both phrases are equal length");
}
}
【问题讨论】:
-
one.compareTo(two);不给你字符串长度。要获得长度,请使用one.length()。 -
我必须使用 compareTo,因为它是作业要求的一部分。
-
compareTo 不返回长度差异,请阅读文档。
-
您需要反转消息或条件的代码错误,因为当 if(length > 0) 意味着“字符串 1 大于字符串 2”时。不是“字符串一小于字符串二”。
标签: java