如何使用while循环遍历哈希映射中的每个项

20 浏览
0 Comments

如何使用while循环遍历哈希映射中的每个项

此问题已经有了答案:

如何遍历HashMap [重复]

我正在创建一个代码块来利用一个名为wordFrequencies的哈希表,该哈希表包含某些单词以及它们在给定字符串中出现的次数。

为了节省细节,这些单词需要排成一行,因此我正在尝试创建代码以将空格添加到单词的开头,直到它们都对齐。我正在通过比较它们的长度来实现这一点。

我的问题是while循环,因为单词只在for循环中定义,我不知道如何定义它以在while循环中使用,因为没有“while each”循环这样的东西。

  // loop to determine length of longest word
        int maxLength = 0;
        for (String word : wordFrequencies.keySet()){
            if (word.length() > maxLength) {
                maxLength = word.length();
                }
            }
        // loop to line up the words in the graph / table
        while (word.length() < maxLength){
            word = " " + word;   // if word is shorter than longest word, add spaces to the start until they line up
        }

admin 更改状态以发布 2023年5月21日
0
0 Comments

主要问题: word在此范围内不可见 - 解决方案: 您需要迭代一次,找到maxLength,然后再迭代一次,以格式化“键”。此外,我不会修改输入键,而是返回一个“格式化副本”,如下所示:

int maxLength = Integer.MIN_VALUE;
for (String word : wordFrequencies.keySet()){
  if (word.length() > maxLength) {
    maxLength = word.length();
  }
}
// a new set for formatted words:
Set formatted = new Set<>(wordFrequencies.size());
// repeat the above loop:
for (String word : wordFrequencies.keySet()){
    // (unfortunately), You have to nest the loop & spend 1 variable:
    String fWord = word;
    while (fWord.length() < maxLength){
        fWord = " " + fWord;   // string concatenation is considered "badong" (bad & wrong)
    }
    // now "put it in the case":
    formatted.add(fWord);
}
// return formatted;

String +更好的方法: 如何在Java中填充字符串?

0
0 Comments

你只需要再次循环遍历该集合。

在循环中使用word = " " + word;的问题是使用加号运算符循环串联字符串不高效。在Java 11+中,您可以使用String repeat(int count)获取空格。在Java 8中,您可以在循环中使用StringBuilder append(String str)获取空格。

此外,您不能编辑HashMap中的键。您可以删除一个条目并添加一个新条目,但最好使用函数格式化单词进行输出。

这里是一个例子:

public class scratch {
 public static void main(String[] args) {
    int maxLength = 0;
    HashMap wordFrequencies = new HashMap<>();
    wordFrequencies.put("bla", 0);
    wordFrequencies.put("blaaaa", 0);
    wordFrequencies.put("blaaaaaaaaaaaaaaaa", 0);
    for (String word : wordFrequencies.keySet()) {
        if (word.length() > maxLength) maxLength = word.length();
    }
    for (String word : wordFrequencies.keySet()) {
        System.out.println(addSpace(word, maxLength));
    }
 }
 public static String addSpace(String word, int maxLength) {
    StringBuilder newWord = new StringBuilder();
    for (int i = 0; i < maxLength - word.length(); i++) {
        newWord.append(" ");
    }
    return newWord.append(word).toString();
    // On Java 11+ you can use String repeat(int count)
    //return " ".repeat(maxLength - word.length()) + word;
}
}

0