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; } } i have 2 methods here and they are almost similar but minWord doesn't show the smallest word, where is the mistake?actually don't undestand where is a problem, i hope you will help me
3 Réponses :
Vous devez définir la première chaîne du tableau comme "longueur minimale" car la valeur initiale "" n'est que de longueur 1 et plus courte que les autres.
Par exemple:
private static String shortest(String test) { String[] words = test.split(" "); String shortest = words[0]; for(int i = 1; i < words.length;i++){ if(words[i].length() < shortest.length()){ shortest = words[i]; } } return shortest; }
Ou sans si dans la boucle:
private static String shortest(String test) { String[] words = test.split(" "); String shortest = null; for(String word : words){ if(shortest == null){ shortest = word; }else if(word.length() < shortest.length()){ shortest = word; } } return shortest; }
Vous pouvez utiliser des flux pour le faire en une seule ligne:
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" }
Vous avez String shortest=" ";
par conséquent, le shortest
a une longueur = 1. Vous pouvez simplement donner au shortest
une très longue chaîne, ou même la chaîne d'entrée elle-même:
public static String minWord(String input){ String[] str = input.split(" "); String shortest=input; // so shortest is initially the largest string for (String word:str){ if (word.length()<shortest.length()) { shortest=word; } } return shortest; }
String shortest = " ";
- il y a déjà un caractère bien avant d'entrer dans la boucle.Si vous utilisez IntelliJ, cela peut être utile pour vous: jetbrains.com/help/idea/ ... Placez le point d'arrêt à l'instruction
if
dans la méthodeminWord()