gpt4 book ai didi

需要 Java SE 数组帮助

转载 作者:行者123 更新时间:2023-12-01 17:09:15 25 4
gpt4 key购买 nike

我的 Java 学校作业需要一些帮助。我们被告知提示用户输入五个单词,然后确定其中最长的单词并打印以控制台最长的单词以及其中的字符数。

现在,我只能通过显示最长的字符数来使用数组对它们进行排序,但我不确定如何显示单词本身。有人可以帮助我吗?请记住,我是编程方面的新手,我的进步仍然只是基础知识,所以请尽量让它对我来说不要太复杂。另外,请随意指出那些冗余代码,因为我知道我有很多。 :)谢谢!

    import java.util.Scanner;
import java.util.Arrays;

class LongestWord
{
public static void main(String [] args)
{
Scanner theInput = new Scanner(System.in);
System.out.println("Please enter your five words");

String fWord = theInput.next();
String sWord = theInput.next();
String tWord = theInput.next();
String fhWord = theInput.next();
String ffWord = theInput.next();

System.out.println(fWord + sWord + tWord + fhWord + ffWord);

int [] wordCount = new int[5];

wordCount[0] = fWord.length();
wordCount[1] = sWord.length();
wordCount[2] = tWord.length();
wordCount[3] = fhWord.length();
wordCount[4] = ffWord.length();

Arrays.sort(wordCount);

System.out.println(wordCount[4]);


}
}

最佳答案

您需要将所有字符串添加到数组中并迭代所有字符串。

示例:

    String [] wordCount = new String[5];

wordCount[0] = fWord;
wordCount[1] = sWord;
wordCount[2] = tWord;
wordCount[3] = fhWord;
wordCount[4] = ffWord;

String longest = "";

longest = wordCount[0]; //get the first array of words for checking

for(String s : wordCount) //iterate to all the array of words
{
if(longest.length() < s.length()) //check if the last longest word is greater than the current workd
longest = s; //if the current word is longer then make it the longest word
}

System.out.println("Longest Word: " + longest + " lenght: " + longest.length());

结果:

Please enter your five words
12345
1234
123
12
1
123451234123121
Longest Word: 12345 lenght: 5

关于需要 Java SE 数组帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24401478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com