0

这是我的任务中我不确定的问题:

该类将包含一个公共方法 nextWord()。读取新行时,使用 String 方法 .split("\s+") 创建行中单词的数组。每次调用 nextWord() 方法都是返回数组中的下一个单词。处理完数组中的所有单词后,读取文件中的下一行。当到达文件末尾时,nextWord() 方法返回值 null。

我已阅读该文件,并将每个单独的字符串存储在一个名为 tokenz 的数组中。

我不确定如何使用一种名为“nextWord”的方法,它一次从 tokenz 中返回每个单词。也许我不明白这个问题?

问题的最后一部分是:

在您的主类中,编写一个名为 processWords() 的方法来实例化 MyReader 类(使用字符串“A2Q2in.txt”)。然后编写一个循环,使用 nextWord() 方法从 MyReader 类中一次获取一个单词,并将每个单词打印在新行上。

我已经想到了这样做的方法,但我不确定如何从我应该编写的 nextWord 方法中返回每个单词。我无法增加计数,因为在返回 String 之后,由于方法已完成处理,因此无法到达 return 语句之后的任何内容。

任何帮助将不胜感激,也许我会以错误的方式解决这个问题?

不能使用数组列表或类似的东西。

这是我的代码。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class A2Q2
{ 

  public static void main (String [] args)
  {
    processWords();
  }

  public static void processWords()
  {
    MyReader reader = new MyReader("A2Q2.txt");

    String[] words = new String[174];

    words[0] = reader.nextWord();
    System.out.println(words[0]);

  }

}

class MyReader
{
  static String name;
  static BufferedReader fileIn;
  static String inputLine;
  static int tokensLength = 0;
  static String[] tokens;
  static int counter = 0;






  // constructor.
  public MyReader(String name)
  {
    this.name = name;
  }


  public static String[] readFile()
  {

    String[] tokenz = new String[174];
    int tokensLength = 0; 



    try
    {
      fileIn = new BufferedReader (new FileReader(name));
      inputLine = fileIn.readLine();



      while(inputLine !=null)
      {
        tokens = inputLine.split("\\s+");  

        for (int i = 0 ; i < tokens.length; i++)
        {
          int j = i + tokensLength;
          tokenz[j] = tokens[i];   
        }
        tokensLength = tokensLength + tokens.length; 
        inputLine = fileIn.readLine();
      }

      fileIn.close();

    }

    catch (IOException ioe)
    {
      System.out.println(ioe.getMessage());
      ioe.printStackTrace();
    }  

    //FULL ARRAY OF STRINGS IN TOKENZ


    return tokenz;

  }

  public static String nextWord()
  {
    String[] tokenzz = readFile();
    //????
    return tokenzz[0];
  }

}
4

2 回答 2

0

这是给你的概念模型。

跟踪您MyReader的状态以了解接下来要返回的值。下面的示例用于tokenIndex决定下一步阅读的位置。

class MyReader
{
  String[] tokens;

  int tokenIndex = 0;

  public String nextWord()
  {
    if(tokens == null || tokens.length <= tokenIndex)
    {
        // feel free to replace this line with whatever logic you want to
        // use to fill in a new line.
        tokens = readNextLine();
        tokenIndex = 0;
    }
    String retVal = tokens[tokenIndex];
    tokenIndex++;

    return retval;
  }   
}

请注意,这不是一个完整的解决方案(例如,它不检查文件结尾),只是一个概念的演示。您可能需要详细说明一下。

于 2013-10-14T22:10:45.197 回答
-1

使用循环并处理数组中的每个元素,一次打印一个?

于 2013-10-14T22:10:54.133 回答