【问题标题】:Strings || Case Sensitive字符串 ||区分大小写
【发布时间】:2022-11-22 23:51:03
【问题描述】:

需要制作一个密码程序,用户在开始时设置密码,密码可以输入3次后程序停止。该程序不能区分大小写。

    public static void main(String[] args) 
{
    Scanner sc = new Scanner(System.in);
    int attempts = 3;
    String password = "";
    System.out.println("Please input your password.");
    Scanner stringScanner = new Scanner(System.in);
    String PASSWORD = stringScanner.next();
    while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
    {
        System.out.print("Enter your password: ");
        password = sc.nextLine();
        if (password.equals(PASSWORD)) 
            System.out.println("Access Granted");
        else 
            System.out.println("Incorrect. Number of attempts remaining: " + attempts);     
    }
        if (attempts < 1) {
            System.out.println("You have entered too many incorrect passwords, please try again later.");
        }
        else {
            System.out.println("Secret: Water is not Wet.");
            }
        }                               
    }

程序按预期打印,但不区分大小写

【问题讨论】:

  • 在比较之前将两个字符串转换为相同的大小写。我确定这只是一个简单的练习,但请注意密码检查应该绝不在现实世界中不区分大小写。

标签: java string switch-statement


【解决方案1】:

你问题的第一部分说The program can not be case sensitive,而之后你说Program prints as expected, but is not case sensitive,所以有点难以理解你想要什么。但是通过查看代码并看到它正在进行区分大小写的比较,并且您对它的行为不满意,我猜您希望这是一个不区分大小写的比较。 在这种情况下,您可以使用String#equalsIgnoreCase!PASSWORD.equalsIgnoresCase(password)

【讨论】:

  • 抱歉,我应该把这个输入放在哪里?对不起,我是 java 的新手,不擅长解释事情
  • while (attempts-- &gt; 0 &amp;&amp; !PASSWORD.equalsIgnoreCase(password))替换你打开while循环的行
  • 太感谢了!!!
  • 它区分大小写,但当我运行它时,我得到了这个输出,不知道为什么。 ``` 请输入您的密码。你好O 输入你的密码:你好不正确。剩余尝试次数:2 秘密:水未湿```
【解决方案2】:

如果您不需要考虑区分大小写,只需执行 password.equalIgnoreCase(PASSWORD) 但是如果您需要确保两者都区分大小写,则可以在比较之前将两个变量都转换为 .toUpperCase

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2016-01-26
    • 2013-05-03
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    相关资源
    最近更新 更多