我在尝试将单词重新添加到单词列表时遇到了一些麻烦。该程序计算单词长度的长度,然后将其存储,以便输出显示如下内容:字长 7 56我已经知道了,所以它可以正确计算字数,但输出没有以正确的字长计算正确的字数。所以应该是 Words of Length 1 0但我的显示长度为 1 97 的单词(这是长度为 2 的单词的正确计数)。我不知道如何解决这个问题。我觉得应该是这样的:wordList[wordCount-1] = word;(-1 是这样我不会得到一个数组越界错误)。 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)问题:如何将单词追加回单词列表数组(单词列表来自文本文件)。不使用数组或哈希。
3 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
在下面的代码中,您将数组索引打印为字长,但索引比字长小 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] );
该行应该结束, i+1, histogram[i]
慕容3067478
TA贡献1773条经验 获得超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
提交
取消