【问题标题】:Check if char is a vowel using switch-case使用 switch-case 检查 char 是否是元音
【发布时间】: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


【解决方案1】:

变量letter 永远不会改变,所以你总是测试同一个字符。当你的 while 循环到达与第一个不同的第一个字符时,它会停止,所以它很快就会停止。

顺便说一句,你可以直接减轻你的代码调用辅音:

int f = 0, g = 0; // vowel and consonant counters
int ind = 0; // character index

while (ind < sentence.length()) {
    char letter = sentence.charAt(ind);
    switch (letter) {
        case 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y':
            f += 1;
            break;

        case 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H', 
             'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'p', 'P', 
             'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W', 
             'x', 'X', 'z', 'Z':
            g += 1;
            break;
                
        default:
            break;
    }

    ind += 1;
}

【讨论】:

  • 是的,我看到我放了ind,而不是我之前在程序中创建的变量a = sentence.length()
  • 我忘了 Q ^^ 看来我应该学习一下我的字母表
  • :) 没人关心 q。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
相关资源
最近更新 更多