所以我正在尝试编写一个代码来查找一组给定字符串的中间字符串,在本例中为3.中间我指的是字典顺序中的中间位置。我写的代码编译并没有问题,但对于字符串的某些组合,它不想正常工作。我运行了一些测试,我在下面的评论中发布了哪些字符串组合给了我一个错误。测试的数字是字符串的实际顺序。有人告诉我,有些组合不满足所有的布尔语句,但我真的不知道如何。我知道这是一个简单的解决方案,但任何帮助将不胜感激。
import java.util.Scanner;
public class MiddleString {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter the first string to compare");
String str1 = in.nextLine();
System.out.println ("Now enter the second string");
String str2 = in.nextLine();
System.out.println ("Good! And finally, the third");
String str3 = in.nextLine();
if ((str1.compareTo(str3) < 0) && (str1.compareTo(str2) < 0) && (str2.compareTo(str3) < 0))
System.out.println("In lexicographic order, the string in the middle will be " + str2);
else if ((str3.compareTo(str1) < 0) && (str1.compareTo(str2) < 0) && (str3.compareTo(str2) < 0))
System.out.println("In lexicographic order, the string in the middle will be " + str1);
else if ((str1.compareTo(str2) < 0) && (str3.compareTo(str2) < 0) && (str1.compareTo(str3) < 0))
System.out.println("In lexicographic order, the string in the middle will be " + str3);
}
}
// TESTS
// str1|str2|str3|result
// A | B | C |pass 123
// B | C | A |pass 231
// M | A | Z |FAIL 213
// A | Z | M |pass 132
// Z | M | A |FAIL 321
// Z | A | M |FAIL 312
//
答案 0 :(得分:0)
import java.util.Scanner;
public class MiddleString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String result = "";
System.out.println("Please enter the first string to compare");
String str1 = in.nextLine();
System.out.println("Now enter the second string");
String str2 = in.nextLine();
System.out.println("Good! And finally, the third");
String str3 = in.nextLine();
if ((str1.compareTo(str2) < 0))
{
if ((str2.compareTo(str3) < 0))
{
result = str2;
} else
{
result = str3;
}
} else
{
result = str1;
}
System.out.println("In lexicographic order, the string in the middle will be " + result);
}
}