简体   繁体   English

Java 字符串比较,按字母顺序打印两个不同的字符串输入

[英]Java string comparison, printing two different string inputs into alphabetical order

We are learning compareTo() method and equals() method, but I am unsure how to properly print the words in alphabetical order.我们正在学习compareTo()方法和equals()方法,但我不确定如何按字母顺序正确打印单词。

I have 2 Strings:我有 2 个字符串:

String firstString;
String secondString;

that are assigned values (elsewhere).被赋值(在其他地方)。

I have tried:我努力了:

System.out.println(firstString.CompareToIgnoreCase(secondString)); 

but am only getting integers in my output as opposed to full words.但我只在我的 output 中得到整数,而不是完整的单词。

As this is homework, I'll only address your stumbling block.由于这是家庭作业,我只会解决你的绊脚石。

As per the documentation , compareToIgnoreCase() (and more generally, compareTo() ) returns an integer, either negative, zero or positive, depending on whether the first parameter's order is less than, the same or greater respectively than the second parameter.根据文档compareToIgnoreCase() (更一般地说, compareTo() )返回一个 integer,负数、零或正数,具体取决于第一个参数的顺序是小于、等于还是大于第二个参数。

You'll need to check the result of compareToIgnoreCase() , then print based on that, for example:您需要检查compareToIgnoreCase()的结果,然后根据该结果进行打印,例如:

if (firstString.compareToIgnoreCase(secondString) > 0) {
    // do something
} else {
    // do something else
}

For those taking the same class, this solves the requirements for the question:对于那些采用相同 class 的人,这解决了问题的要求:

  if (firstString.compareTo(secondString) < 0) {
     System.out.println(firstString + " " + secondString);
  }
        
  else {
     System.out.println(secondString + " " + firstString);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM