java按字典顺序排序三个单词

时间:2013-06-03 04:04:16

标签: java

我是Java编程语言的新手,想要创建一个程序,使用扫描程序类读取三个单词,并按字母顺序排列在主方法中执行此操作的三个单词,例如用户输入Tom Harry Dick,答案应该是Dick Harry和Tom ..我尝试使用if语句来比较使用java compareTo()的字符串,但if语句不会为我返回任何内容,因为main方法是无效的。

public class SortWords {

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);

    String firstWord;
    String secondWord;
    String thirdWord;


    System.out.println("Enter three words seperated by white space");

    firstWord = userInput.next();
    System.out.println(firstWord);

    secondWord = userInput.next();
    System.out.println(secondWord);

    thirdWord = userInput.next();
    System.out.println(thirdWord);

}

}

2 个答案:

答案 0 :(得分:3)

然后尝试读取数组元素然后对该数组进行排序

public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);
    String[] strings = new String[3];

    for (int i = 0; i < strings .length; i++)
    {
        System.out.println("Please enter name");
        strings [i] = input.next();
    }
}

Arrays.sort(strings);

答案 1 :(得分:1)

“我尝试使用if语句来比较使用java compareTo()的字符串,但if语句不会为我返回任何内容,因为main方法是无效的。”

这是不正确的。

首先,我们没有说if语句'返回任何内容',我们说它选择执行或不执行语句块({ }包含的语句块)是否基于condition(由( )括起来)计算为true或false。 (当elseelse if被投入时类似的想法)

其次,这不受其所处方法的返回类型的影响,因为它与返回无关。

您应该使用print和println语句打印出三个字符串比较的结果,因为这是main方法,并且没有更高的方法可以返回。

相关问题