2014-06-25 65 views
0

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

现在,我只设法通过显示最长的字符数来排列它们,但我不知道如何显示这个词本身。有人可以帮助我,请记住我是编程的总新手,我的进步仍然只是在基础知识,所以请尽量不要让我太复杂。另外,随时查找那些冗余代码,因为我知道我有很多。 :) 谢谢!

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]); 


} 
    } 
+1

您不需要排序只是为了找到最长的单词,也不需要将所有单词存储在内存中。逐一阅读,只存储到目前为止最长的单词。 – Henry

+1

你做得很好,只是多想一点,你应该可以自己编写代码! – Abubakkar

回答

3

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

样本:

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 
+0

嗨嗨Rod,感谢您的帮助,但我仍然无法得到它。这部分你说的(String s:wordCount),当我编译时,它说需要的字符串找到int,不兼容的类型。谢谢! –

+0

@ alan_ogz83 editted见上面评论 –

+0

感谢棒但它仍然无法编译。现在它仍然说不兼容的类型需要字符串找到整型,但它声明在你键入的区域wordCount [0] = fWord.length();向前。 :) –

2

您需要将所有的字存储到阵列,并得到最大值排序后根据其长度。

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(); 
0

而不是把长到一个数组,你应该把所有词语的数组,然后使用for/while循环它们并检查每个字符串的长度与前一个字符串的比较以记录最大长度字符串。

或者另一种方式可能是使用循环读取字符串,并且可以执行相同的逻辑来比较长度而不使用额外的数组。