我必须创建一个程序,它接受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。只有从文件中读取时才会这样做。
你说你必须按字典顺序排列3个字符串。我认为这意味着你必须按顺序输出3个字符串,从低到高,而不是只找到最小的字符串。
下面是一些Java代码,用最少的比较来说明执行此操作所需的逻辑:
public static void main(String[] args)
{
String[][] tests = {
{"a", "b", "c"},
{"a", "c", "b"},
{"b", "a", "c"},
{"b", "c", "a"},
{"c", "a", "b"},
{"c", "b", "a"},
};
for(String[] s : tests)
{
order(s[0], s[1], s[2]);
}
}
static void order(String first, String second, String third)
{
int firstSecond = first.compareTo(second);
int firstThird = first.compareTo(third);
int secondThird = second.compareTo(third);
if(firstSecond < 0)
{
if(firstThird < 0)
{
if(secondThird < 0)
{
print(first, second, third);
}
else
{
print(first, third, second);
}
}
else
{
print(third, first, second);
}
}
else if(secondThird < 0)
{
if(firstThird < 0)
{
print(second, first, third);
}
else
{
print(second, third, first);
}
}
else
{
print(third, second, first);
}
}
private static void print(String... arr)
{
System.out.println(Arrays.toString(arr));
}
输出:
[a, b, c]
[a, b, c]
[a, b, c]
[a, b, c]
[a, b, c]
[a, b, c]