所以我试着写一个代码来查找一组给定字符串的中间字符串,在本例中是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
//发布于 2018-06-05 07:27:29
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);
}
}https://stackoverflow.com/questions/50689952
复制相似问题