【发布时间】:2021-07-23 03:55:44
【问题描述】:
问题是:编写一个 Java 程序,要求用户提供字母表中的单个字符。根据用户输入打印元音或辅音。如果用户输入不是字母(在 a 和 z 或 A 和 Z 之间),或者是长度 > 1 的字符串,则打印适当的描述性错误消息。
我做了一个 switch 语句,成功地告诉你是元音还是辅音,但如果用户输入的长度超过一个字符,我不知道如何给出错误消息。
import java.util.Scanner;
public class VowelKL{
public static void main(String[] args){
int i=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter a single letter from the alphabet: ");
char letter=input.next().charAt(0);
switch(letter)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : i++;
}
if(i==1)
System.out.println("You entered the letter " + letter + " and it is a Vowel!");
else
if((letter>='a' && letter<='z')||(letter>='A' && letter<='Z'))
System.out.println("You entered the letter " + letter + " and it is a Consonant!");
else
System.out.println("You did not enter a single character from the alphabet, please try again.");
}
}
【问题讨论】:
标签: java char switch-statement