如何将此 FOR 循环转换为 WHILE 循环,以便它也计算辅音?到目前为止,我知道如何使用 While 循环进行基本计数器...
import java.util.Scanner;
public class VowelsCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a string: ");
String str = in.nextLine();
System.out.print("Number of Vowels in the string: " + vowCount(str) + "\n");
}
public static int vowCount(String str) {
int count = 0;
for (int index = 0; index < str.length(); index++) {
if (str.charAt(index) == 'a' || str.charAt(index) == 'e' ||
str.charAt(index) == 'i' || str.charAt(index) == 'o' ||
str.charAt(index) == 'u') {
count++;
}
}
return count;
}
}
最佳答案
while()
循环在其参数处有一个终止语句
,这意味着您必须将终止设置为 while 参数,而不是初始化和递增索引。 编辑 index
变量必须在循环之前初始化。
在您的情况下:
while(index != str.length()){
//rest of the statement, those from your for loop
index++;
}
关于java - 如何将此 FOR 循环转换为 WHILE 循环,以便它也计算辅音? (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51588383/