【发布时间】:2020-06-22 20:07:22
【问题描述】:
我正在创建一段代码来获取名为 wordFrequencies 的哈希图,其中包含一些单词以及它们在给定字符串中出现的次数。
为了节省细节,单词需要对齐,所以我尝试创建代码以在单词的开头添加空格,直到它们全部对齐。我通过比较它们的长度来做到这一点。
我遇到的问题是 while 循环,因为 word 仅在 for 循环中定义,我不知道如何定义它以在 while 循环中使用,因为知道诸如“while”之类的东西每个”循环。
// 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
}
【问题讨论】:
-
@xerx593 是的。我需要在单词的开头添加空格,直到与最长单词的长度相同。 for 循环处理确定最长单词的长度,但它是我正在努力解决的 while 循环
-
您可能想要使用 String.format() ,它使用 printf 格式并且可以左右对齐值。