如何从ArrayList(Java)打印最短的字符串

问题描述 投票:1回答:3

好的,所以目标是打印最小长度的字符串(例如,如果输入是“co”,“college”,“college”,“university”我想要打印出co。我已经尝试过college.compareTo( ____);以及其他一些东西,但我似乎无法将它打印出来。也不是什么花哨的东西(如果你已经读过/有头脑第一版第二版那么我们在第五章/ 6)我宁愿您是否可以将我链接到一个视频,该视频将显示解释需要做什么的过程,但任何事情都有帮助:一直在盯着这个编码几个星期,有点大脑死了它...这是我到目前为止(接受用户的字符串);

ArrayList <String> colleges = new ArrayList <String> ( ) ;
    String input;
    Scanner scan = new Scanner(System.in) ;
    while (true) {
        System.out.println("Please enter your college (Press Enter twice to quit) ");
        input = scan.nextLine();
        if (input.equals ("")) {
            break;
        }
        else {
            colleges.add(input.toUpperCase () );
        }// end of if else statement
    }// end of while loop

    System.out.println("The following " + colleges.size() + " colleges have been entered:");

    for ( String college : colleges) {
         System.out.println("\n" + college );
         System.out.println("Character count: " +  college.length( ) );
    }// end of for each loop
java arrays string arraylist
3个回答
4
投票

这些是您需要的步骤:

  1. 创建自定义Comparator<String>以根据字符串的长度对字符串进行排序。
  2. 使用自定义比较器和Collections.min()方法从列表中获取最短的字符串。

在其最紧凑的版本中,您的代码看起来像这样(假设列表中没有null字符串):

String shortest = Collections.min(colleges, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
});

0
投票

您可以使用以下逻辑打印给定arrayList中的最小字符串

string smallString = "";
for ( String college : colleges) {
    if(smallString.length() == 0 && college.length() != 0)
    {
        smallString = college ;
    }
    else if(college.length() < smallString.length() && college.length() != 0)
    {
        smallString = college;
    }
}
println("Smallest string is: " + smallString );

0
投票
public static String SmallestString(ArrayList <String> collegeArray){
    String smallest = "";
    System.out.println("");
    for(String string :collegeArray){
        //if input-string is null or empty
        if(string == null || string.trim() == "" || string.trim().length()==0){
            System.out.println("Emtpy String Encountered");
            continue;
        }
        if(smallest == ""){
            smallest = string;
            continue;
        }
        if(string.length() < smallest.length()){
            smallest = string;
        }
    }
    return smallest;
}

叫它:System.out.println("\nSmallest String: " + SmallestString(colleges));

© www.soinside.com 2019 - 2024. All rights reserved.