【问题标题】:How do I check if user input is a number and if it's the same as another variable in the same while loop?如何检查用户输入是否为数字,以及它是否与同一个 while 循环中的另一个变量相同?
【发布时间】:2021-05-07 14:33:53
【问题描述】:

我正在尝试将我在两周的 C# 中学到的所有内容都实现到一个模拟 ATM 类型的应用程序中。所以请记住,虽然有更好的方法来编写或简化我的代码,但我正在努力坚持我现在所知道的,以便更好地理解它。

  1. 这就是我目前正在尝试做的事情:用户输入一个 用户名(用户名),我需要检查它是否匹配 正确的用户名,我知道这与 if 语句有关,但是,我 需要它还能够识别用户是否输入了 字符串,如果还有其他内容,它将给出错误。带一个int I 知道我可以试试int.TryParse,我不知道字符串等价物是什么 就是这样。
  2. 用户输入 pin (pinCode) 和上面类似,但我知道如何 检查这是否是数字而不是字符串并将其与 正确的密码;我不明白如何显示两个不同的 基于该条件的错误消息。如果出现一条错误消息 用户没有输入数值(pinNumericalError)并且 其他如果引脚不匹配(pinError)。我假设两个“如果 语句”在 else 语句中(这甚至可能吗?),但我 不知道 TryParse 条件的语法是什么样的 在它上面。
  3. 然后一旦用户名和密码都正确(基于 以上条件)我可以继续菜单或我计划的任何内容 接下来做。两者都嵌套在父 while 循环中吗?
namespace ATM
{
    class AtmLogin
    {
        static void Main()
        {
            //User input
            string userName;
            int pinCode;

            //Correct values to proceed
            string correctUserName = "Chad Warden";
            int correctPinCode = 6969;
            
            //Error messages
            string userNameError = "Enter a valid username";
            string pinError = "Enter a valid pin";
            string pinNumericalError = "Enter a valid numerical pin";
            string namePinError = "Either your username or pin was invalid, try again.";
            
            //Welcome message
            Console.WriteLine("Welcome to PSTriple Banking!");   
         
            //Username prompt - checks if userName is a string and not a number or anything else and compares it to correctUserName
            Console.WriteLine("User name:");
            userName = Console.ReadLine();
            
            //Pin prompt - checks if pinCode is a number and not a string or anything else and compares it to correctPinCode    
            while (true)
            {
                Console.WriteLine("Pin:");
                if (int.TryParse(Console.ReadLine(), out pinCode) && pinCode == correctPinCode) {
                    
                    break;
                }
                else
                {
                    
                    Console.WriteLine(pinError);
                }
            }

          

            Console.ReadKey();
        }
    }
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    用户名必须至少包含一个字母,但 pin 必须包含零个字母,以便您可以使用 stackoverflow 中的此答案

      bool isIntString = "your string".All(char.IsDigit)
    

    如果字符串是数字则返回true

    bool isIntString = !"your string".All(char.IsDigit)
    

    如果字符串包含至少一个非数字,则返回true

    https://stackoverflow.com/a/18251942/2826614

    【讨论】:

      猜你喜欢
      • 2015-01-02
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2021-11-29
      • 2021-03-21
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多