打印未知数字列表

时间:2014-11-28 18:46:11

标签: java arrays for-loop while-loop

我创建了一个程序,用于检查文本文件中是否显示了特定长度的单词数。我想打印我的程序找到的具有此特定长度的单词数,然后打印出该单词列表。但是,单词列表首先在我的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();

2 个答案:

答案 0 :(得分:0)

如果您想避免在while循环中打印单词,可以将println从循环中取出。如果您不想,则不必将每个单词添加到数据结构中。您可以将每个单词附加到“wordBuffer”StringBuffer(String Buffer连接比String更快更有效),有关此问题的更多信息请阅读: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();

这是你在找什么?

答案 1 :(得分:0)

此上下文中数组的问题是数组在初始化后具有不可变大小。如果您要检索可变集合,则需要一个没有此类限制的收集器。 ArrayList可以达到此目的。

public static void countLetters(PartArray part, int num) throws Exception {
Scanner inputFile = new Scanner(new File("2of12inf.txt"));

int count = 0;
ArrayList<String> words = new ArrayList();

while( inputFile.hasNext() ){
  String word = inputFile.next();

  if (word.length() == num)
  {
    count++;
    //expandArray (part , 2*MAX_SIZE);
    //System.out.println(word);
    words.add(word);//adding each word to a new index with each iteration
  } 
}
System.out.println("I found " + count + " " + num + "-letter words.");
System.out.println("The list of words is: ");

for (String w in words) {//for each word in the words ArrayList
   System.out.println(w);//print out the values
}

inputFile.close();