gpt4 book ai didi

java - Java 中的字长

转载 作者:行者123 更新时间:2023-12-01 17:20:21 28 4
gpt4 key购买 nike

在查找文件中的字长作业中,我无法理解一些代码。注意:我使用的环境是 Blue J,带有来自 dukelearntoprogram.com 的库,这是下载 Blue J 的链接,http://www.dukelearntoprogram.com/course3/index.php 。我创建了一个名为 countWordLength 的 void 方法,其参数 FileResource 称为资源,以及一个名为 counts 的整数数组。此方法应返回文件中特定长度的字数。例如:2个长度为2的单词:My as。他们给了我这个作业的代码,但我不理解我的 countWordLength 方法中的以下代码。

for (String word : resource.words()) {
int finalLength = 0;
int totalLength = word.length();
if (Character.isLetter(word.charAt(0)) == false) {
finalLength = totalLength-1;
}
else {
finalLength = totalLength;
}
if (Character.isLetter(word.charAt(totalLength-1)) == false && totalLength > 1) {
finalLength = finalLength-1;
}


if (finalLength >= counts.length) {
counts[counts.length-1] += 1;

}
else {
counts[finalLength] += 1;
}

我不明白的具体部分是含义或用处

if (finalLength >= counts.length) {
counts[counts.length-1] += 1;

}
else {
counts[finalLength] += 1;
}

如果我的问题不清楚,并且您可能需要我的代码的更多部分,请告知。任何帮助将受到高度赞赏。

最佳答案

说明:

int finalLength = 0;
int totalLength = word.length();
if (Character.isLetter(word.charAt(0)) == false) {
finalLength = totalLength-1;
}
else {
finalLength = totalLength;
}

Above lines are initiating lengths. If 1st character is not alphabet, then reducing length.

if (Character.isLetter(word.charAt(totalLength-1)) == false && totalLength > 1) {
finalLength = finalLength-1;
}

If last character is not alphabet, removing one more character but a special condition added here that it is we reduce word length only if it's length > 1

if (finalLength >= counts.length) {
counts[counts.length-1] += 1;
}

This might be bit tricky for you. If calculated length is greater than array we assigned, we are adding count to last one. Ex: Let's say they assigned array with 20 and if got word length as 30, then we will assign this word count to last index (19).

else {
counts[finalLength] += 1;
}

If length is less than size allowed than we will add to that respective index.

关于java - Java 中的字长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61305423/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com