繁体   English   中英

需要Java SE阵列帮助

[英]Java SE array help needed please

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

您需要将所有单词存储到数组中,并根据其长度排序后获得最大值。

 String[] words = ....//Store all words into this array.

 Arrays.sort(words, new Comparator<String>() {

         @Override
         public int compare(String o1, String o2) {
             return o2.length() - o1.length();
         }
     });

 System.out.println(words[0]);

或者,如果您使用的是Java-8,那么您将更容易获得结果,

String longWord=
       Arrays.stream(words).max((o1, o2)->o1.length()-o2.length()).get();

而不是将长度放入数组中,您应该将所有单词放入数组中,然后使用for / while循环它们,并检查每个字符串的长度与上一个相比,以记录最大长度的字符串。

或者另一种方法是使用循环读取字符串,您可以执行比较长度的相同逻辑,而无需使用其他数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM