【发布时间】:2017-09-15 20:30:27
【问题描述】:
我正在尝试制作一个拆分字符串的程序,并返回具有 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;
}
}
【问题讨论】:
-
tokens[i].... 为什么你会认为tokens至少有i+1元素? -
在
if(isVowel(tokens[i].charAt(j)))中是什么让你认为tokens[i]确实存在?
标签: java arrays string split do-while