0

我在如何创建一个按字符读取文件的新有序映射时遇到了麻烦。这是我的程序的开始

public class Practice {

  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the file name to random write: ");
    String fileName = keyboard.nextLine();

    System.out
        .print("Enter nGram length, 1 is like random, 12 is like the book: ");
    int nGramLength = keyboard.nextInt();
    keyboard.close();

    Practice rw = new Practice(fileName, nGramLength);
    rw.printRandom(500);
  }

  private HashMap<String, ArrayList<Character>> all;
  private int nGramLength;
  private String fileName;
  private StringBuilder theText;
  private static Random generator;
  private String nGram;

  public Practice(String fileName, int nGramLength) {
    this.fileName = fileName;
    this.nGramLength = nGramLength;
    generator = new Random();
    makeTheText();
    setRandomNGram();
    setUpMap(); // Algorithm considered during section.  
  }

  private void makeTheText() {
    Scanner inFile = null;
    try {
      inFile = new Scanner(new File(fileName));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    theText = new StringBuilder();
    while (inFile.hasNextLine()) {
      theText = theText.append(inFile.nextLine().trim());
      theText = theText.append(' ');
    }
  }

  public void setRandomNGram() {
    generator = new Random();
    int temp = theText.length() - nGramLength - 1;
    int start = generator.nextInt(temp);
    nGram = theText.substring(start, start + nGramLength);
  }

  // Read theText char by char to build a OrderedMaps where
  // every possible nGram exists with the list of followers. 
  // This method need these three instance variables:    
  //    nGramLength   theText  all
  private void setUpMap() {
    // TODO: Implement this method
      for(int i = 0; i < nGramLength; i++)
      {
          ArrayList<Character> key = all.get(i);
      }
      }

  // Print chars random characters.  Please insert line breaks to make your
  // output readable to the poor grader :-)
  void printRandom(int howMany) {
    // TODO: Implement this method
  }
}

我需要处理最后两种方法,但我对如何遍历哈希图感到困惑

4

2 回答 2

1

您可以通过迭代 aHashMap来迭代它entrySet()。这将为您提供关键和价值:

for (Map.Entry<String, ArrayList<Character>> entry : all) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

或者,您可以只迭代它的keySet()or valueSet(),但听起来好像您想要这里的键和值。

于 2013-11-27T23:15:34.353 回答
0

答案是您不会在地图上进行迭代。地图没有迭代器,因为那没有意义。它会在键值或值上迭代什么。解决方案是将您的键或值转换为集合。您可以使用 values 方法(返回值的集合)和 keySet 方法(返回映射中的一组键)来执行此操作,然后您可以调用这些集合的迭代器方法。

于 2013-11-27T22:52:35.907 回答