Closed. This question needs debugging details。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5个月前关闭。
                    
                
        

    public class maxWord {
    public static void main(String[] args) {
        String str = "“@2434 rfdfd4f fff“";
        System.out.println(maxWord(str));
        System.out.println(minWord(str));
    }

    public static String maxWord(String input){
        String[] str = input.split(" ");
        if (str.length==0) return null;
        String longest=" ";
        for (String word:str){

            if (word.length()>longest.length()) {
                longest=word;

            }
        }
        return longest;
    }

    public static String minWord(String input){
        String[] str = input.split(" ");
        String shortest=" ";
        for (String word:str){
            if (word.length()<shortest.length()) {
                shortest=word;

            }
        }
        return shortest;
    }
}


我在这里有2种方法,它们几乎相似,但是minWord没有显示最小的单词,哪里出了错误?

其实不要不明白哪里出了问题,希望您能帮我

最佳答案

您可以使用流来在一行中进行操作:

public static void main(String[] args) {
    String string = "This is a long sentence";
    List<String> wordList = Arrays.asList(string.split("\\s+"));

    String shortest = wordList
            .stream()
            .min(Comparator.comparingInt(String::length))
            .orElse(null);
    System.out.println(shortest); //prints "a"

    String longest = wordList
            .stream()
            .max(Comparator.comparingInt(String::length))
            .orElse(null);
    System.out.println(longest); //prints "sentence"
}

10-07 22:44