在列表中找到最大的字符串

时间:2018-09-03 08:07:51

标签: arraylist

我需要在ArrayList中找到最大的字符串,然后打印出来。我的代码目前无法正常工作。

public class Solution {
    private static List<String> strings;

    public static void main(String[] args) throws Exception {

   BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        strings = new ArrayList<String>();

        for (int i = 0; i < 5; i++) {
            String n = reader.readLine();
            strings.add(n);

        }

        String largestString = strings.get(0);
        for (int i = 0; i < strings.size(); i++) {
            if (strings.get(i).length() > largestString.length()) {
                largestString = strings.get(i);
                System.out.println(largestString);
            }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    String value = null;
    int length = 0;
    for (int i = 0; i < 5; i++) {
        String n = reader.nextLine();
        if (n != null && n.length() > length) {
            length = n.length();
            value = n;
        }

    }
    System.out.println("Largest String : " + value + " of length : " + length);
}