1

我想要做的是,当使用我的程序的人在没有任何内容的情况下点击输入时,它不会导致错误这是程序的一部分:

Console.WriteLine("4.-Ya no quiero jugar >.<");
int opc = Convert.ToInt16(Console.ReadLine());

switch (opc)
{
    case 1:
        Console.WriteLine("omg");
        break;

    case 2:
        Console.WriteLine("wtf");
        break;

    default:
        Console.WriteLine("Cant do that  >.>");
        Console.ReadKey();
        break;

    etc.
}

事情是我使用整数,我试图这样做

string opc1=console.readline();

if (opc =="")
{
    console.writeline("nope,try again");
}
else
{ // Brace was omitted in original - Jon
    int opc = Convert.ToInt16(Console.ReadLine());

    switch (opc)

    blah blah.

以及它的不同组合 >.< 和默认值对此不起作用

我希望有人能帮我解决它>.<

4

6 回答 6

10

检查Int16.TryParse方法。

Int16如果用户输入不是(负 32768 到正 32767)允许范围内的数字,这将允许您退出程序或执行其他操作。

示例代码可以在 MSDN 条目 ( Int16.TryParse Method ) 中找到。

于 2009-12-14T18:51:19.093 回答
4

首先,将您设置Console.ReadLine()为一个变量。然后检查您设置的变量是否为空或为空。另外,我建议使用 Int16 类的 TryParse 方法,因为它根据转换是否成功返回 true 或 false。

此外,您不需要将您的转换ReadLine为整数,因为您也可以打开字符串。因为ReadLine已经是 a String,所以不需要转换。但是,如果您需要整数,请尝试以下操作:

String lineIn = Console.ReadLine();

if (!String.IsNullOrEmpty(lineIn))
{
    Int16 myNum;
    if (Int16.TryParse(lineIn , out myNum))
    {
            switch(myNum)
            {
                    case 1:
                    ...
                    default:
                    ...
            }
    }
}
于 2009-12-14T18:52:06.003 回答
1

我认为你想要的是 int.Parse(...)

于 2009-12-14T18:51:30.670 回答
0

您可能会考虑使用try catch语句进行错误处理...

于 2009-12-14T18:51:18.070 回答
0

尝试解析:

string str;
short val;
while(!short.TryParse(str=Console.ReadLine(), out val))
{
    Console.WriteLine("Cant do that  >.>");
}
于 2009-12-14T18:54:30.973 回答
0

为了得到一个整数,我通常使用这样的递归函数

private int GetInt()
{
     try
     {
         return int.parse(Console.Readline().Trim());
     } 
      catch (exception e) 
     {
         Console.WriteLine(string.format("{0} Please try again", e.message);
         return GetInt();
     }
}
于 2009-12-14T19:06:08.030 回答