gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:51:31 24 4
gpt4 key购买 nike

我必须创建一个程序,它接受 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com