-5

我想做这样的事情-

using System;

class MainClass
{
    public static void Main ()
    {
        bool? input;
        Console.WriteLine ("Are you Major?");
        input = bool.Parse (Console.ReadLine ());
        IsMajor (input); 

    }


    public static void IsMajor (bool? Answer)
    {
        if (Answer == true) {
            Console.WriteLine ("You are a major");
        } else if (Answer == false) {
            Console.WriteLine ("You are not a major");
        } else {
            Console.WriteLine ("No answer given");
        }
    }

}

在这里,如果用户没有给出答案并简单地按回车,变量输入必须存储值null,输出必须是No answer given

在我的代码中,输入truefalse工作正常。

但是如果没有给出输入并按下回车,编译器会抛出异常

System.FormatExeption has been thrown
String was not recognized as a valid Boolean

那么如何获取null存储在变量中的值input以便输出为No answer given

这里,

问题字符串未被识别为有效的布尔 C#

显然不是重复的,因为它不想直接从键盘获取空输入。如果不能采用这样的输入,那么可空类型的用途是什么,因为也有解决方法?

4

3 回答 3

4
bool input;
Console.WriteLine("Are you Major?");
if (!bool.TryParse(Console.ReadLine(), out input))
{
    Console.WriteLine("No answer given");
}
else
{
    //....
}

或使用C# 7

if (!bool.TryParse(Console.ReadLine(), out bool input))
{
    Console.WriteLine("No answer given");
}
else
{
    // Use "input" variable
}
// You can use "input" variable here too
于 2017-12-28T10:11:31.090 回答
2
bool? finalResult = null;
bool input = false;

Console.WriteLine("Are you Major?");

if (bool.TryParse(Console.ReadLine(), out input))
    finalResult = input;
}

如果输入不能被解析为or ,finalResult则使用上述技术。nulltruefalse

于 2017-12-28T10:16:43.007 回答
-2

您可以用 try-catch 包围您的解析,并在 catch 时(因此,如果用户给出的不是 true 或 false )将 input 设置为 null。

于 2017-12-28T10:02:55.867 回答