我不断收到一个数组越界的异常
问题描述:
我想做一个程序分裂字符串,并返回带有3个或更多元音的字符串,我不断收到一个数组超出界限的异常。我不知道如何在方法结尾返回一个数组。我不断收到一个数组越界的异常
我的程序中显然无法看到问题在哪里?
public class SplitWords {
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
final int MIN_SIZE = 4;
int size = 0;
do{
System.out.println("How many words are you typing(min " + MIN_SIZE + "): ");
size = scan.nextInt();
}while(size < MIN_SIZE);
scan.nextLine();
String[] myarray = new String[size];
for(int i = 0; i < myarray.length; i++){
System.out.println("Type the sentence in the position " + i);
myarray[i] = scan.nextLine();
}
System.out.println("The words which have 3 or more vowels are: " + findVowels(myarray));
}
public static String findVowels(String[] myarray){
for(int i = 0; i < myarray.length; i++){
String[] tokens = myarray[i].split(" ");
int count = 0;
for(int j = 0; j < myarray.length; j++) {
if(isVowel(tokens[i].charAt(j))){
count++;
}
}
if(count > 3){
break;
}
}
return null;
}
public static boolean isVowel(char ch){
switch(ch){
case 'a':
case'e':
case'i':
case'o':
case'u':
case'y':
return true;
}
return false;
}
}
答
为什么要将字符串拆分为令牌?也调用String [],我猜你或者意味着char []或者String,因为你正在做的是创建一个字符串数组,并且像字符串数组一样是一个字符串。只要使用 “字符串” 不 “的String []”
+0
即时通讯非常抱歉的家伙,即时通讯第一年的初学者,这是一个assigment和它会帮我在我的考试 – JaneSus
答
这是问题
for(int j = 0; j < myarray.length; j++) {
if(isVowel(tokens[i].charAt(j))){
count++;
}
}
当你分割字符串
String[] tokens = myarray[i].split(" ");
你为什么不使用,而不是tokens.length myarray.length,并使用令牌[j]不是我,我是你有的字符串数量的计数器。
整合上述改变后,你的代码看起来应该是这样
public static String findVowels(String[] myarray){
for(int i = 0; i < myarray.length; i++){
String[] tokens = myarray[i].split(" ");
int count = 0;
for(int j = 0; j < tokens.length; j++) {
String str = tokens[j];
for (int j2 = 0; j2 < str.length(); j2++) {
if(isVowel(str.charAt(j2))){
count++;
}
if(count > 3){
break;
}
}
}
}
return null;
}
这不会给任何异常,但我与此代码的逻辑很惊讶,因为你是在结束返回null该方法无论如何。
'tokens [i]'....为什么你会认为'tokens'至少有'i + 1'个元素? – lurker
在'if(isVowel(tokens [i] .charAt(j)))'是什么让你认为'token' [i]'实际存在? –