首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找“中间”字符串

查找“中间”字符串
EN

Stack Overflow用户
提问于 2018-06-05 07:10:10
回答 1查看 100关注 0票数 0

所以我试着写一个代码来查找一组给定字符串的中间字符串,在本例中是3。我说的中间是指字典顺序中的中间。我写的代码可以编译并工作,没有问题,但对于某些字符串组合,它不想正常工作。我运行了一些测试,并在下面的评论中发布了字符串的组合给了我一个错误。测试得到的数字是字符串的实际顺序。有人告诉我,一些组合并不能满足所有的布尔语句,但我真的看不出是如何做到的。我知道这是一个简单的解决方案,但任何帮助都将不胜感激。

代码语言:javascript
复制
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
//
EN

回答 1

Stack Overflow用户

发布于 2018-06-05 07:27:29

代码语言:javascript
复制
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);
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50689952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档