C#Console.read()没有显示正确的数字输入?

时间:2014-12-19 00:36:50

标签: c#

 String name = Console.ReadLine();
            System.Console.WriteLine("input name");
            System.Console.WriteLine("hello {0}", name);
            int hello = Console.Read();
            System.Console.WriteLine("First number input" + hello);
            int hello2 = Console.Read();
            Console.ReadKey();
            System.Console.WriteLine("Second number input" + hello2);

在这行代码中,它显示输入的名称,然后显示第二个键的第一个键(即hello)的输入,但无论我做什么,它总是显示为13.如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

Console.Read不解析输入字符。它返回一个整数是误导性的,但这实际上是输入的单个字符的数字表示。

相反,请使用Console.ReadLine,并将结果解析为数字。

int hello;
while(!int.TryParse(Console.ReadLine(), out hello)
{
   // This will happen if the user types something that's not a number
   Console.WriteLine("Please enter a valid number:"); 
}
Console.WriteLine("First number input" + hello);

答案 1 :(得分:0)

您可以这样修改: //assumed you want to get integer values String name = Console.ReadLine(); System.Console.WriteLine("input name"); System.Console.WriteLine("hello {0}", name); int hello = Convert.ToInt16(Console.ReadLine()); System.Console.WriteLine("First number input" + hello); int hello2 = Convert.ToInt16(Console.ReadLine()); Console.ReadKey(); System.Console.WriteLine("Second number input" + hello2);

答案 2 :(得分:0)

我在您的代码中发现了一些基本问题,并将我的想法放在下面的评论中。

String name = Console.ReadLine(); // Shows the cursor without a prompt to the user
System.Console.WriteLine("input name");
System.Console.WriteLine("hello {0}", name);
int hello = Console.Read(); // This line reads the new line character (13) from the above line
System.Console.WriteLine("First number input" + hello); // Displays 13 (new line character if the user doesn't enter any value)
int hello2 = Console.Read();
Console.ReadKey(); // Exits the console as soon as a user press a key
System.Console.WriteLine("Second number input" + hello2); // This is never displays to the user

我想到在向你展示所有问题之后重新考虑它。这就是我提出的问题。看一看。由于您尝试使用用户输入构建一个简单的应用程序,因此您必须考虑用户输入和输出的流程。

int firstNumber;
int secondNumber;
string name = string.Empty;

do
{
    Console.Clear();
    Console.Write("What is your name?");
    name = Console.ReadLine();        
} while (string.IsNullOrEmpty(name));

Console.WriteLine("Hello {0}", name);

do
{
    // This will happen if the user types something that's not a number
    Console.Clear();
    Console.WriteLine("Hello {0}", name);
    Console.Write("Please enter the first number:");
} 
while (!int.TryParse(Console.ReadLine(), out firstNumber));

do
{
    // This will happen if the user types something that's not a number
    Console.Clear();
    Console.WriteLine("Hello {0}", name);
    Console.WriteLine("First number is: " + firstNumber);
    Console.Write("Please enter the second number:");
}
while (!int.TryParse(Console.ReadLine(), out secondNumber));

Console.WriteLine("Second number is: " + secondNumber);
Console.Read();