给定一个字符串,打印字符串中存在的字母数。 输入: 第一行输入包含一个整数T,表示测试用例的数量。 T测试用例的描述如下。每个测试用例包含一个字符串。 输出: 打印字符串中存在的字母数。
这个问题我一直试图在eclipse上解决这个问题,但它一直在我的代码的第7行抛出ArrayIndexoutOfBoundsException。我试着理解我做错了什么,但我无法做到。 有人可以在这里解释什么是错的。我附上了代码。
public class solution {
public static void main(String[] args){
String s = "baibiasbfi" ;
int count =0;
for(int i=0;i<=s.length();i++){
char[] a= s.toCharArray();
if(a[i]>='a'&& a[i]<='z'||a[i]>='A'&&a[i]<='Z')
count++;}
System.out.println(count);
}
}
答案 0 :(得分:0)
i <= s.length();
for loop
中的应为:
i < s.length();
ArrayIndexOutOfBoundsException
被抛出:
表示已使用非法访问数组 指数。该指数为负数或大于或等于 数组的大小。
答案 1 :(得分:0)
在java中,数组从0
到length-1
。您正在使用循环将其与i<=s.length()
进行比较。这意味着你的循环回放了数组的长度。这给出了ArrayIndexoutofBoundsException
。
用以下代码替换你的循环:
for(int i=0;i<s.length();i++){