【问题标题】:Can not get it to accept a "letter" input无法让它接受“字母”输入
【发布时间】:2015-04-13 14:55:03
【问题描述】:

请原谅我,我是编程新手,但完全享受我迄今为止所学到的东西。所以我的问题是;我正在尝试编写一个程序,提示用户输入一个字母,然后返回该字母是元音还是辅音。问题是我无法让它接受字母输入。如果强制如“user_input = 'a'”那样,它将接受它。但不是作为一种选择。我知道缺少一些简单的东西。

public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    int user_input;

    System.out.print("Enter a letter: ");
    user_input = in.nextInt();//<--line of error

    if (user_input == 'a')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='e')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='i')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='o')
    {
        System.out.println("Vowel");
    }
    else if (user_input =='u')
    {
        System.out.println("Vowel");
    }
    else
    {
        System.out.println("Consonant");
    }
}

提前感谢您的宝贵时间。

【问题讨论】:

标签: java


【解决方案1】:

既然你读的是一个字符,你应该使用字符类型。此外,您想读取下一个字符,而不是下一个 int。 .next() 将读取下一个字符串,然后 charAt(0) 仅获取第一个字符。

System.out.print("Enter a letter: ");
char user_input = in.next().charAt(0);

如果你想不区分大小写:

char user_input = in.next().toLowerCase().charAt(0); 

您还可以通过使用逻辑“或”而不是单独的ifs 来减少代码的重复

if (user_input == 'a'
 || user_input =='e'
 || user_input =='i'
 || user_input =='o'
 || user_input =='u')
{
    System.out.println("Vowel");
}
else
{
    System.out.println("Consonant");
}

但是,您可能更喜欢switch 语法方法

switch (user_input) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        System.out.println("Vowel");
        break;
    default:
        System.out.println("Consonant");
        break;
}

【讨论】:

  • 或者,OP 可以使用类似 this 的 switch 语句
  • @mstbaum 您更喜欢设置变量而不是像我一样设置大小写?我不太确定我是否理解您的不同建议
  • 我想我跳过了你已经提供的开关语法部分,只是没有注意到它。我的错。
  • 这很有帮助,谢谢。它起作用了,我添加了一条错误消息,以防输入其他内容(例如一个字母或一个数字)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 2015-10-04
相关资源
最近更新 更多