所以我在课堂上给了这个作业,以便进行计数元音应用。我不知道我的代码有什么问题,但请看看。
package com.practice;
import java.util.*;
public class CountVowels {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int vowels = 0;
System.out.print("Enter text: ");
String text = input.nextLine();
int last = text.length() - 1;
while (last > 0) {
char temp = text.charAt(counter);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') {
vowels++;
}
counter++;
last++;
}
System.out.println("The number of vowels are: " + vowels);
}
}
答案 0 :(得分:2)
您的程序具有无限循环,因此调用IndexOfBoundException
。如果U想要从结束循环循环,则需要递减last
变量。写下--last;
而不是last++
,并在while (last >= 0)
上更改您的周期条件。要从字符串的开头到结尾循环,请更改int last = text.length() - 1;
上的int last = 0;
和while (last < text.length())
上的周期条件。您可以选择许多不同的方法来解决这个问题,但是您已经理解了这一点。
答案 1 :(得分:0)
你必须按照以下方式纠正错误
Scanner input = new Scanner(System.in);
int vowels = 0;
System.out.print("Enter text: ");
String text = input.nextLine();
System.out.println(text);
int last = text.length() - 1;
while (last >= 0) {
char temp = text.charAt(last);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') {
vowels++;
}
last--;
// in your case this one ++ cause StringIndexOutOfBoundsException
}
System.out.println("The number of vowels are: " + vowels);
答案 2 :(得分:-1)
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int vowels = 0;
System.out.print("Enter text: ");
String text = input.nextLine();
int last = text.length() - 1;
for(int i=0;i<text.length();i++)
{
char temp = text.charAt(i);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') {
vowels++;
}
}
System.out.println("The number of vowels are: " + vowels);
}
输出是:
输入文字:santhosh
元音的数量是:2