所以我试图找到用户输入的字符串中的所有大写字母但我不断收到此运行时错误:
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)
这是我的代码,用于查找大写字母并打印它们:
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++){
记住数组索引从ZERO开始.
the number of 16-bit Unicode characters in the string
因为循环从ZERO开始,循环应终止于长度-1.
标签:java,string,uppercase,printing,lang
来源: https://codeday.me/bug/20191008/1870990.html