我在如何创建一个按char读取文件char的新有序映射时遇到了麻烦。这是我的计划的开始
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
}
}
我需要处理最后两个方法,但我对如何遍历hashmap感到困惑
答案 0 :(得分:1)
您可以通过迭代HashMap
来迭代entrySet()
。这将为您提供关键和价值:
for (Map.Entry<String, ArrayList<Character>> entry : all) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
或者,您只能在其keySet()
或valueSet()
上进行迭代,但听起来好像您需要密钥和值。
答案 1 :(得分:0)
答案是你没有在地图上进行迭代。地图没有迭代器,因为这没有任何意义。什么会对键值或两者进行迭代。解决方案是将您的键或值转换为集合。您可以使用values方法(返回值的集合)和keySet方法(在地图中返回一组键)来执行此操作。然后,您可以调用这些集合的迭代器方法。