需要 Java SE 数组帮助

标签 java arrays string

我的 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/

相关文章:

javascript - 如何根据数组上有多少索引来显示动态的 div 集

java - 想要将startswith()方法用作!startswith()吗?

python - 使用Python3.x中的格式打印一个字符串中的列表、字符串和字典

java - Firebase - 当数据根据用户记录更新时如何使适配器逻辑

java - "Anoynmous methods"有趣的行为

java - 有条件地改变列表适配器android

c - 在结构中声明 int 数组

c# - Asp.Net DataList 绑定(bind) ImageUrls 数组

java - 使用 BufferedReader 读取数组?

java - 自定义 Spring Scope 不适用于消息 channel