所以我试图找到用户输入的字符串中的所有大写字母,但我不断收到此运行时错误:
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++){
记住数组索引从零开始。
the number of 16-bit Unicode characters in the string
因为循环从零开始,所以循环应该在长度为 1 处终止。
关于java - 在java中查找字符串的所有大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150730/