我必须创建一个程序,该程序使用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 ");
}
}
答案 0 :(得分:1)
如果只想使用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。仅当它从文件读取时才这样做。
答案 1 :(得分:0)
您说您必须按字典顺序排序 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]