我在嘗試將單詞重新添加到單詞列表時遇到了一些麻煩。該程序計算單詞長度的長度,然后將其存儲,以便輸出顯示如下內(nèi)容:字長 7 56我已經(jīng)知道了,所以它可以正確計算字?jǐn)?shù),但輸出沒有以正確的字長計算正確的字?jǐn)?shù)。所以應(yīng)該是 Words of Length 1 0但我的顯示長度為 1 97 的單詞(這是長度為 2 的單詞的正確計數(shù))。我不知道如何解決這個問題。我覺得應(yīng)該是這樣的:wordList[wordCount-1] = word;(-1 是這樣我不會得到一個數(shù)組越界錯誤)。 import java.io.*;import java.util.*;public class Project2{ static final int INITIAL_CAPACITY = 10; public static void main (String[] args) throws Exception { // ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Project2 <input filename>\n\n"); // i.e. C:\> java Project2 dictionary.txt System.exit(0); } int[] histogram = new int[0]; // histogram[i] == # of words of length n /* array of String to store the words from the dictionary. We use BufferedReader (not Scanner). With each word read in, examine it's length and update word length frequency histogram accordingly. */ String[] wordList = new String[INITIAL_CAPACITY]; int wordCount = 0; BufferedReader infile = new BufferedReader( new FileReader(args[0]) ); while ( infile.ready() ) { String word = infile.readLine(); // # # # # # DO NOT WRITE/MODIFY ANYTHING ABOVE THIS LINE # # # # # if (wordCount == wordList.length) wordList = upSizeArr(wordList); // test to see if list is full. If needed do an up size (just like Lab#3)問題:如何將單詞追加回單詞列表數(shù)組(單詞列表來自文本文件)。不使用數(shù)組或哈希。
3 回答

白豬掌柜的
TA貢獻(xiàn)1893條經(jīng)驗 獲得超10個贊
在下面的代碼中,您將數(shù)組索引打印為字長,但索引比字長小 1(還記得histogram[word.length()-1]++嗎?);
// PRINT WORD LENGTH FREQ HISTOGRAM
for ( int i = 0; i < histogram.length ; i++ )
System.out.format("words of length %2d %d\n", i,histogram[i] );
該行應(yīng)該結(jié)束, i+1, histogram[i]

慕容3067478
TA貢獻(xiàn)1773條經(jīng)驗 獲得超3個贊
改變:
if (word.length() > histogram.length)
histogram = upSizeHisto(histogram, wordLength);
到
if (word.length() >= histogram.length)
histogram = upSizeHisto(histogram, wordLength+1);
和
histogram[word.length() - 1]++;
到
histogram[word.length()]++;
添加回答
舉報
0/150
提交
取消