繁体   English   中英

当输入某些数据或错误答案时,使程序绝对不执行任何操作

[英]Making a program do absolutely nothing when certain data or wrong answer is put in

我有个疯狂的主意,如果将错误的数据放入控制台,我希望程序不执行任何操作。 例如字母,奇怪的字符。 我想要的只是十进制数字和一个可接受的句点。 如果输入了错误的数据,我希望程序停留在该位置,并且在按Enter键后绝对不执行任何操作。

我的心态认为:

if (sum != decimal)
{
   // Don't do anything, just leave it as is. 
    code I have no clue about. 

}

现在,您必须在考虑,不能将数据类型用于if语句! 也许可以,但是它对我不起作用。 对不起,我是个大菜鸟。

try
{

    Console.WriteLine("Put in the price of the product");

    string input = Console.ReadLine();
    decimal sum = Convert.ToDecimal(input);

    if (sum <= 100)
    {
        decimal totalprice = sum * .90m;
        Console.WriteLine("Your final price is {0:0:00}", totalprice);

    }

}


catch
{

}

我还认为,也许一条try-catch语句也可以工作,但是同样,我也不知道该添加什么。

如果您的答案可能是菜鸟安全且可以解释。 (因为我想学习这些东西是如何工作的概念),这很好。

视觉示例:

stackoverflowimage

当您按Enter键时,除了输入正确的数据类型外,什么都不会发生,程序将继续。

数据类型未写入控制台。 从控制台输入中只能检索字符串。 字符串"2"是什么类型-十进制,整数,字节,字符串? 您所能做的就是尝试从输入字符串中解析某种类型:

Int32.TryParse("2", out value)

对于您的情况:

Console.WriteLine("Put in the price of the product");
string input = Console.ReadLine();
decimal sum;
if (!Decimal.TryParse(input, out sum))
{
    Console.WriteLine("Decimal number cannot be parsed from your input.");
    return;
}

if (sum <= 100)
    Console.WriteLine("Your final price is {0:0:00}", sum * 0.90M);

UPDATE

  • Decimal.TryParse-将数字的字符串表示形式转换为其等效的Decimal 返回值指示转换是成功还是失败。 如果转换失败,它不会引发异常。
  • 运算符 -不是运算符。 逻辑否定运算符(!)是一元运算符,它会否定其操作数。 它是为bool定义的,并且仅当其操作数为false时才返回true

因此, if (!Decimal.TryParse(input, out sum))验证转换是否if (!Decimal.TryParse(input, out sum)) 然后,我向用户发送了一条示例消息,并退出了方法(如果这是您的Main方法,那么程序将终止。但是,这全都不是您最初有关解析字符串的问题了。

试试这个(注意while / break配对):

while (true)
{
    string input = Console.ReadLine();
    decimal sum;

    if (Decimal.TryParse(input, out sum) == true)
    {
        if (sum <= 100)
        {
            decimal totalprice = sum * .90m;
            Console.WriteLine("Your final price is {0:0:00}", totalprice);
            break;  // break out of while
        }
    }
}

如果使用的转换函数无法将传递的字符串转换为请求的类型,我相信会引发异常。 通常,应避免异常以控制程序流,而应保留真正的意外情况。 相反,您应该使用不会抛出异常的方法,而是返回一个指示成功或失败的值。 使用此ind,您可以尝试:

    try
    {
        Console.WriteLine("Put in the price of the product");
        decimal sum;
        // Repeat forever (we'll break the loop once the user enters acceptable data)
        while (true)
        {
            string input = Console.ReadLine();
            // Try to parse the input, if it succeeds, TryParse returns true, and we'll exit the loop to process the data.
            // Otherwise we'll loop to fetch another line of input and try again
            if (decimal.TryParse(input, out sum)) break;
        }

        if (sum <= 100)
        {
            decimal totalprice = sum * .90m;
            Console.WriteLine("Your final price is {0:0:00}", totalprice);
        }
    }
    catch
    {

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM