gpt4 book ai didi

java - StringIndexOutOfBound 异常

转载 作者:行者123 更新时间:2023-12-04 12:43:23 25 4
gpt4 key购买 nike

我试图编写一个程序,它从用户那里获取一个字符串,并告诉用户该字符串中小写字母、大写字母、空格等的数量。但我收到一条错误消息:StringIndexOutOfBound。

public class CharacterCount {
public static void main(String args[])throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter you string here");
String s = br.readLine();
System.out.println(s);

int upperCase = 0;
int lowerCase = 0;
int specialCase = 0;
int whiteSpace = 0;
int number = 0;

for(int i=1;i<=s.length();i++)
{
char ch = s.charAt(i);
if(Character.isAlphabetic(ch))
{
if(Character.isUpperCase(ch))
{
upperCase++;
}
else
{
lowerCase++;
}
}

if(Character.isWhitespace(ch))
{
whiteSpace++;
}
if(Character.isDigit(ch))
{
number++;
}
else
{
specialCase++;
}
}

System.out.println("-----------------------------------------------------------------");
System.out.println("The following are the results:");
System.out.println("-----------------------------------------------------------------");
System.out.println(lowerCase+" :Lower Case Characters");
System.out.println("-----------------------------------------------------------------");
System.out.println(upperCase+" :Upper Case Characters");
System.out.println("-----------------------------------------------------------------");
System.out.println(whiteSpace+" :White Space");
System.out.println("-----------------------------------------------------------------");
System.out.println(specialCase+" :Special Characters");
System.out.println("-----------------------------------------------------------------");
System.out.println(number+" :Digits");
System.out.println("-----------------------------------------------------------------");
System.out.println("----------------************THE END************------------------");
System.out.println("-----------------------------------------------------------------");

}
}

最佳答案

您正在迭代错误的索引。 Java 索引从 0 开始,因此 length() 字符的字符串具有从 0length()-1 的索引。

你的循环应该是

for(int i=0;i<s.length();i++)

关于java - StringIndexOutOfBound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27634167/

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