我需要一些幫助,這裏與我的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]);
}
}
您不需要排序只是爲了找到最長的單詞,也不需要將所有單詞存儲在內存中。逐一閱讀,只存儲到目前爲止最長的單詞。 – Henry
你做得很好,只是多想一點,你應該可以自己編寫代碼! – Abubakkar