如何将Console.Readkey转换为int c# [英] How do I convert a Console.Readkey to an int c#

查看:681
本文介绍了如何将Console.Readkey转换为int c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户输入键转换为int,用户将输入1到6之间的数字。

I am trying to convert a user input key to an int, the user will be entering a number between 1 and 6.

这是我到目前为止所拥有的坐在一个方法中,它不起作用,但抛出一个格式异常是未处理的。

This is what i have so far sitting inside a method, its not working, yet throwing a format exception was unhandled.

        var UserInput = Console.ReadKey();



        var Bowl = int.Parse(UserInput.ToString());

        Console.WriteLine(Bowl);

       if (Bowl == 5)
        {
            Console.WriteLine("OUT!!!!");
        }
        else
        {
            GenerateResult();
        }

    }

感谢您的帮助!

推荐答案

简单地说你试图将 System.ConsoleKeyInfo 转换为 int

Simply said you are trying to convert System.ConsoleKeyInfo to an int.

在您的代码中,当您调用 UserInput.ToString()你得到的是代表当前对象的字符串,而不是持有字符如你所料。

In your code, when you call UserInput.ToString() what you get is the string that represents the current object, not the holding value or Char as you expect.

要获得 Char 作为字符串你持有可以使用 UserInput.KeyChar.ToString()

To get the holding Char as a String you can use UserInput.KeyChar.ToString()

此外,您必须检查 ReadKey在尝试使用 int.Parse 方法之前,获取数字。因为 Parse 方法在转换数字失败时抛出异常。

Further more ,you must check ReadKey for a digit before you try to use int.Parse method. Because Parse methods throw exceptions when it fails to convert a number.

所以它看起来像这样,

int Bowl; // Variable to hold number

ConsoleKeyInfo UserInput = Console.ReadKey(); // Get user input

// We check input for a Digit
if (char.IsDigit(UserInput.KeyChar))
{
     Bowl = int.Parse(UserInput.KeyChar.ToString()); // use Parse if it's a Digit
}
else
{
     Bowl = -1;  // Else we assign a default value
}

和你的代码:

int Bowl; // Variable to hold number

var UserInput = Console.ReadKey(); // get user input

int Bowl; // Variable to hold number

// We should check char for a Digit, so that we will not get exceptions from Parse method
if (char.IsDigit(UserInput.KeyChar))
{
    Bowl = int.Parse(UserInput.KeyChar.ToString());
    Console.WriteLine("\nUser Inserted : {0}",Bowl); // Say what user inserted 
}
else
{
     Bowl = -1;  // Else we assign a default value
     Console.WriteLine("\nUser didn't insert a Number"); // Say it wasn't a number
}

if (Bowl == 5)
{
    Console.WriteLine("OUT!!!!");
}
else
{
    GenerateResult();
}

这篇关于如何将Console.Readkey转换为int c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆