gpt4 book ai didi

java - 在java中查找字符串的所有大写字母

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:30 26 4
gpt4 key购买 nike

所以我试图找到用户输入的字符串中的所有大写字母,但我不断收到此运行时错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)

我觉得很愚蠢,但我就是想不通,oracle 甚至在关于 java.lang.StringIndexOutOfBoundsException 的页面上谈论 charAt

这是我查找大写字母并打印它们的代码:

import java.io.*;
import java.util.*;

public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}

我非常感谢任何意见和/或帮助。

最佳答案

for(int y = 0; y <= z; y++){

应该是

for(int y = 0; y < z; y++){

记住数组索引从零开始。

String length返回

the number of 16-bit Unicode characters in the string

因为循环从零开始,所以循环应该在长度为 1 处终止。

关于java - 在java中查找字符串的所有大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150730/

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