简体   繁体   English

[Java]努力按字母顺序排列字符串

[英][Java]Struggling to put string in alphabetical order

I am trying to create a void method that uses 3 string parameters and puts the strings in alphabetical order.我正在尝试创建一个使用 3 个字符串参数并将字符串按字母顺序排列的 void 方法。 So far I have used if statements and I believe the if statements are correct however I keep getting a message that says "void cannot be converted into string" I am suppose to use a void method and I am very confused this is my code到目前为止,我已经使用了 if 语句,并且我相信 if 语句是正确的,但是我不断收到一条消息,上面写着“void 无法转换为字符串”我想使用 void 方法,我很困惑这是我的代码

public class AlphabeticalOrder {

    public static void inOrder(String s1, String s2, String s3) {
        if (s1.compareTo(s2) < 0 && s1.compareTo(s3) < 0)
            if (s2.compareTo(s3) < 0)
                System.out.println(s1 + s2 + s3);
            else
                System.out.println(s1 + s2 + s3);
        else if (s2.compareTo(s1) < 0 && s2.compareTo(s3) < 0)
            if (s1.compareTo(s3) < 0)
                System.out.println(s2 + s1 + s3);
            else
                System.out.println(s2 + s3 + s1);
        else if (s3.compareTo(s1) < 0 && s3.compareTo(s2) < 0)
            if (s2.compareTo(s1) < 0)
                System.out.println(s3 + s2 + s1);
            else
                System.out.println(s3 + s1 + s2);
    }

    public static void main(String[] args) {
        String ans1 = inOrder("abc", "mno", "xyz");
        System.out.println(ans1);
    }
}

Change your main method to this:将您的主要方法更改为:

public static void main(String[] args)
{
    inOrder("abc", "mno", "xyz");
}

Your function returns "void", which means "nothing", so you can't assign it to a variable or print it.您的 function 返回“void”,表示“无”,因此您不能将其分配给变量或打印它。

The better way to do this is almost certainly to have your method return a String[] , but if your assignment is to return void , then this is the best you've got.更好的方法几乎可以肯定是让您的方法返回String[] ,但如果您的任务是返回void ,那么这是您所拥有的最好的方法。

in addition to JoshuaD answer, I propose you use more convenient way to sort this using Stream API .除了 JoshuaD 的回答,我建议您使用更方便的方式使用Stream API 对其进行排序。

private static void inOrder(String s1, String s2, String s3) {
    Stream.of(s1, s2, s3).sorted().forEach(System.out::println);
}

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

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