【发布时间】:2021-01-17 14:20:55
【问题描述】:
我正在尝试检查字符串中的每个字符是否在 while 循环中使用 switch 语句。到目前为止,我有这个:
//f and g - vowel and consonant count
int f, g, ind;
f = 0;
g = 0;
ind = 0;
char letter = sentence.charAt(ind);
while (letter != sentence.charAt(ind)) {
switch (letter) {
case 'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y':
f += 1;
ind += 1;
break;
//in case it's a number, the code will pass to the next char
case 1, 2, 3, 4, 5, 6, 7, 8, 9:
ind += 1;
break;
//in case it's a special character, the code will pass to the next char
case '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '-', '_', '+', '=', '\\', '|', ';', ':', ',', '.', '/', '?':
ind += 1;
break;
default:
g += 1;
ind += 1;
break;
}
}
由于某种原因,它只为两个变量返回 0。有什么建议?顺便说一句,我很喜欢,所以不要太意思(如果我做了一些愚蠢的事情,一点点就好了)。此外,如果有人有更有效的方法来检查 char 是否是特殊字符,那将不胜感激。提前致谢。
【问题讨论】:
-
为什么呢?你写这段代码是为了什么?
-
它实际上只是计算输入字符串中的元音和辅音。是上学的它不一定有目的。
-
如果你问作业问题,记得要明确:meta.stackoverflow.com/questions/334822/…,因为大多数作业问题与我们在现实生活中编写的那种代码几乎没有任何关系,所以回答你的那种做作业和“真正的问题”是非常不同的。 (例如,你永远不会写这种代码,你只会使用正则表达式匹配器)
-
啊,是的。应该指定的。这实际上只是一个学习练习。
-
您仍然可以:请编辑您的帖子 =)
标签: java loops while-loop switch-statement