当我尝试数元音和辅音时,似乎什么也没发生

问题描述

我需要使用while循环。 错误:二进制运算符||的操作数类型错误。 第一种类型:布尔值 secod类型:char

假定字母A,E,I,O和U是元音;还有什么是 辅音。编写一个程序,提示用户输入字符串 (仅包含字母-不包含数字),并显示数字 字符串中的元音和辅音。使用while循环。

这是我的代码

Scanner input = new Scanner(system.in);
        
   System.out.print("Enter a sentence: ");
   String s = input.nextLine();
   s = s.toupperCase().trim();
        
   int vowels = 0;
   int consonants = 0;  
        
   int i = 0;
    
   while (i < s.length()){
   char ch = s.charat(i);
            
       if(ch == 'A' || ch == 'E' || ch == 'I'|| ch = 'O' || ch == 'U')
       {
       ++vowels;
       }
       else {
       consonants++;
                }
i++;
    System.out.println("The number of vowels is " + vowels);
    System.out.println("The number of consonants is " + consonants);
            
        }
    
        
    }
    
}

解决方法

我为我的程序找到了另一个解决方案。您可以在下面看到新程序。这个正在运行。没问题。

Scanner input = new Scanner(System.in);
        
System.out.print("Enter a sentence: ");
String s = input.nextLine();

int vowels = 0;
int consonants = 0; 
        
int i = 0;
    
while (i < s.length()){
    if (Character.isLetter(s.charAt(i))) {
        if (Character.toUpperCase(s.charAt(i)) == 'A' ||
           Character.toUpperCase(s.charAt(i)) == 'E' ||
           Character.toUpperCase(s.charAt(i)) == 'I' ||
           Character.toUpperCase(s.charAt(i)) == 'O' ||
           Character.toUpperCase(s.charAt(i)) == 'U') 
           vowels++;
           }else{
           consonants++;
           }
           i++;
        }       
        System.out.println("The number of vowels is " + vowels);
        System.out.println("The number of consonants is " + consonants);

输出: 跑: 输入一句话:我们需要计划下一个夏天 元音数为9 辅音个数为6 建立成功(总时间:1分0秒)