java - 从 3 个字符串中找出字典顺序最小的字符串

标签 java computer-science lexicographic lexicographic-ordering

我必须创建一个程序,它接受 3 个字符串并按字典顺序对它们进行排序。我发现为此你必须使用 compareTo() 方法,问题是当我尝试执行 if 语句时,我看到它们是 int 而不是字符串,而且我不知道如何甚至可以显示哪一个是最小的,因为有很多不同的选择。有没有更简单的方法来使用该方法(不允许使用数组或任何东西)?

import java.util.Scanner;
public class SetAQuestion2
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner (System.in);
        String first, second, third;

        System.out.print("Type three words: ");
        first = scan.next();
        second = scan.next();
        third = scan.next();

        int oneA = (first. compareTo (second));
        int oneB = (first.compareTo (third));

        int secondA = (second. compareTo (first));
        int secondB = (second.compareTo(third));

        int thirdA = (third.compareTo(first));
        int thirdB = (first.compareTo (second));

        System.out.println("The smallest word lexicographically is ");
    }
}

最佳答案

如果您只想使用 compareTo() 和简单的 if/else 语句,那么您可以设置另一个字符串变量并比较单词。例如:

String first, second, third, result;
System.out.println("Type three words: ");
first = scan.next();
second = scan.next();
third = scan.next();

if (first.compareTo(second) > 0)
    result = second;
else
    result = first;

if (result.compareTo(third) > 0)
    result = third;
System.out.println("The smallest word lexicographically is " + result);

您还可以使用三元表达式代替 if 语句:

result = first.compareTo(second) > 0 ? (second.compareTo(third) > 0 ? third : second) : (first.compareTo(third) > 0 ? third : first);

我还建议使用 try-with-resources使用扫描仪时,它会自动关闭,因此:

try (Scanner scan = new Scanner(System.in)) {
    // rest of the code here
}

编辑:

正如 Andy Turner 在他的评论中提到的,如果从 System.in 读取,您不必关闭扫描仪或使用 try-with-resources。仅当从文件中读取时才执行此操作。

关于java - 从 3 个字符串中找出字典顺序最小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52154047/

相关文章:

java - 将数据获取到Android应用程序的最佳方法?

java - 将 ArrayList 拆分为多个 ArrayList

java - 如何将两个按字典顺序排列的字符串 ArrayList 合并到一个新的第三个 ArrayList 中?

c - 如何正确地将数组指针传递给 C 中的函数

sorting - 在 Hbase 中的日期之间搜索

c++ - 非 ascii 字符的字典顺序排序

java - 如何使用 BCEL 更改静态字段的值?

java - 来自包含文件(文件 :///path/to/file) to a java. nio.FileChannel

java - 从整数填充二进制数数组时遇到问题

c++ - 为什么 List 类必须包含一个 Node 结构作为私有(private)成员 C++