【问题标题】:Java:If user type 'y'||'Y' quiz begins,'n'||'N' quiz end.For rest,it shows invalid. I want to show invalid when user type word starting with y or nJava:如果用户输入'y'||'Y'测验开始,'n'||'N'测验结束。对于休息,它显示无效。当用户键入以 y 或 n 开头的单词时,我想显示无效
【发布时间】:2019-10-19 16:04:48
【问题描述】:

我希望程序仅在收到“y”、“Y”、“N”或“n”时运行。它不适用于其他角色。然而,当用户用 y 或 n 写一个多于 1 个字母的单词时(例如 yddh、ndhdh 等),程序仍然运行。请建议我能做什么。我尝试将 'a' 作为字符串,但在 if-else 语句中显示错误,因为字符串无法与 == 运算符的 char 进行比较。

   import java.util.Scanner;
   class Main {
   static char a;


   public static void main(String[] args) {
   System.out.println("Do you want to play this quiz?");
   System.out.println("Type 'Y'for Yes or 'N' for no. It's case Insensitive.");
   Scanner sc=new Scanner(System.in);
   a=sc.next().trim().charAt(0);

   if (a=='n'||a=='N')
   {System.out.println("Thanks for downloading!");
    System.exit(0);}

   else if ((a !='n'&&a !='N') && (a !='y'&& a !='Y'))
   {System.out.println("Invalid Syntax");
   System.exit(0);}


   else if(a=='y'||a=='Y')
   {System.out.println("Welcome to the quiz");}
    }
   }

【问题讨论】:

  • 检查 y/Y 和 n/N,其余部分使用 else,无需第三次检查。 (如果你的程序说只允许大写 Y/N 但它也允许小写,这会让用户感到困惑)

标签: java if-statement char java.util.scanner


【解决方案1】:

根据 Subramanian Mariappan 和 Yasham 的回答,您可以使用 equalsIgnoreCase() 方法缩短代码,如下所示:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        System.out.println("Do you want to play this quiz?");
        System.out.println("Type 'Y'for Yes or 'N' for no. It's case Insensitive.");
        Scanner sc = new Scanner(System.in);
        String userInput = sc.next();

        if (userInput.equalsIgnoreCase("N")) {
            System.out.println("Thanks for downloading!");
            System.exit(0);
        } else if (userInput.equalsIgnoreCase("Y")) {
            System.out.println("Welcome to the quiz");     
        } else  {
            System.out.println("Invalid Syntax");
            System.exit(0);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2019-02-12
    • 1970-01-01
    • 2018-11-05
    • 2012-12-29
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多