我创建了一个程序,用于检查文本文件中出现的特定长度的单词数量。我想打印我的程序找到的特定长度的单词数,然后打印出该单词列表。但是,单词列表首先在我的 while
循环中打印,因为我必须在此循环之外打印计数。我是否必须将这个未知的编号列表放入一个数组中,然后返回该数组以在 main 方法中打印它,以便第二次打印?这是我到目前为止所拥有的:
public static void countLetters(PartArray part, int num) throws Exception{
Scanner inputFile = new Scanner(new File("2of12inf.txt"));
int count = 0;
while( inputFile.hasNext() ){
String word = inputFile.next();
if (word.length() == num)
{
count++;
expandArray (part , 2*MAX_SIZE);
System.out.println(word);
}
}
System.out.println("I found " + count + " " + num + "-letter words.");
System.out.println("The list of words is: ");
inputFile.close();
最佳答案
如果你想避免在while循环中打印单词,你可以将println从循环中取出。如果您不愿意,则不必将每个单词添加到数据结构中。您可以将每个单词附加到“wordBuffer”StringBuffer(字符串缓冲区连接比字符串更快、更高效),有关此问题的更多信息请阅读:http://www.javaworld.com/article/2076072/build-ci-sdlc/stringbuffer-versus-string.html
像这样:
int count = 0;
StringBuffer wordBuffer = new StringBuffer ("");
while( inputFile.hasNext() ){
String word = inputFile.next();
if (word.length() == num)
{
count++;
//Adding \n assuming you want new line between elements
wordBuffer.append(word+"\n");
}
}
System.out.println("I found " + count + " " + num + "-letter words.");
System.out.println("The list of words is: "wordBuffer);
inputFile.close();
这是您要找的吗?
关于java - 打印未知数量的单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194445/