【发布时间】:2015-05-27 18:10:13
【问题描述】:
我写了一个作业来尝试计算字符串中每种元音的数量。
它编译得很好,但似乎在 switch 语句上循环,尽管谷歌搜索了大约一个小时,但我看不出我做错了什么。
请帮忙! =]
import java.util.Scanner;
public class assignment3b
{
public static void main(String[] args)
{
int alpha=0, epsilon=0, india=0, oscar=0, uniform=0, position=0, length;
String input;
char letter;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the vowel parse-o-matic");
System.out.println("\nThis program will count all lower case vowels in whatever you type.");
System.out.print("\nPlease enter the word you'd like to have parsed : ");
input = scan.next();
System.out.println("\n\nThe word " + input + " has: "); // reprints the word before stripping spaces
input = input.replaceAll("\\s+",""); // Removes whitespace so they don't get counted.
while (position < input.length());
{
letter = input.charAt(position);
switch (letter)
{
case 'a':
alpha = alpha + 1;
position = position +1;
break;
case 'e':
epsilon = epsilon + 1;
position = position +1;
break;
case 'i':
india = india + 1;
position = position +1;
break;
case 'o':
oscar = oscar + 1;
position = position +1;
break;
case 'u':
uniform = uniform + 1;
position = position +1;
break;
default:
position++;
break;
}
System.out.println("a's = " + alpha);
System.out.println("e's = " + epsilon);
System.out.println("i's = " + india);
System.out.println("o's = " + oscar);
System.out.println("u's = " + uniform);
System.out.println("\nOther characters = " + (input.length() - alpha -epsilon - india -oscar - uniform));
}
}
}
【问题讨论】:
-
您的
printlns 都在 while 循环之后的 {} 中,这可能就是为什么... -
附带说明,为了帮助我的强迫症,请使用
position++或position = position + 1,但请不要同时使用。这让我哭了。 -
另外,如果您要增加位置,则无需在每种情况下增加位置。而且根本不需要位置,你可以在
String.toCharArray上快速枚举。 -
旁注:北约拼音字母表,这似乎启发了您自己的灵感,使用带有 f 的
alfa,以及echo而不是epsilon -
switch不会“循环”。这基本上是表达长if/elseif/elseif/.../else树的好方法。
标签: java loops switch-statement