Java字符串比较结果异常:gh被误判为大于hi的问题
问题分析与修复
你的问题核心是**compareTo返回值的逻辑判断完全搞反了**,同时输出文案也存在错误:
String.compareTo()的返回规则:- 返回正数:当前字符串(one)的字典序大于目标字符串(two)
- 返回负数:当前字符串(one)的字典序小于目标字符串(two)
- 返回0:两个字符串完全相等(不是长度相等)
- 输入
gh和hi时,gh.compareTo(hi)返回负数('g'的Unicode值103小于'h'的104),但你的代码把负数判定为“one大于two”,这就导致了错误输出。
修正后的代码
package com.mycompany._3; 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 compareResult = one.compareTo(two); if(compareResult > 0){ System.out.print("String one is greater than string two."); }else if (compareResult < 0) { System.out.print("String one is less than string two."); }else{ System.out.print("Both phrases are equal."); } } }
关键修正点
- 变量名从
length改为compareResult,避免误解(该值与字符串长度无关) - 反转了
>0和<0对应的输出文案,匹配compareTo的返回逻辑 - 修正相等情况的输出文案,明确是字符串内容相等而非长度相等
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

