gpt4 book ai didi

java - 计算大写字母

转载 作者:行者123 更新时间:2023-11-29 08:12:10 24 4
gpt4 key购买 nike

好的,我必须将一个字符串传递给显然存储在 args[0] 中的主要方法。然后计算大写字母出现的次数。出于某种原因,我似乎没有正确计算大写字母的出现次数。这是作业,有什么想法吗?提前致谢。

package chapter_9;    

public class Nine_Fifteen {

public static void main(String[] args) {
int caps = 0;

for(int i = 0;i < args.length;i++) {
if (Character.isUpperCase(args[0].codePointCount(i, i))){
caps++;
}


System.out.println("There are " + caps + " uppercase letters");

}
}
}

最佳答案

问题是您对 String.codePointCount 的使用:

Returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.

这不是您想要的 - 您将其传递给 Character.isUpperCase,这是不正确的。

您确定需要处理非 BMP Unicode 吗?如果不是,如果您使用 charAt(i) 来获取特定索引处的 char,您的代码会简单很多。您还想从 0 循环到 args[0].length() 正如 Kevin 提到的那样。我建议将 args[0] 部分提取到一个单独的字符串变量开始,以避免混淆:

String text = args[0];
for (int i = 0; i < text.length(); i++) {
// Check in here
}

我不会为您完成代码,因为它是家庭作业,但希望这足以让您继续前进。

关于java - 计算大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7559517/

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