C# 为什么我需要2个控制台。ReadLine();暂停控制台?
我只是在学习c#,我喜欢在继续之前了解一切 我遇到的问题是我需要2个控制台。ReadLine();暂停控制台。如果我只使用1,程序在输入后结束。那么,为什么它需要2个readline方法而不是其他方法呢?有什么想法吗 请注意,在我的代码中,我已经注释掉了1个readline方法,这是我希望我的程序工作的方式,但它没有。然而,删除注释可以让程序工作,但我不明白为什么C# 为什么我需要2个控制台。ReadLine();暂停控制台?,c#,console.readline,C#,Console.readline,我只是在学习c#,我喜欢在继续之前了解一切 我遇到的问题是我需要2个控制台。ReadLine();暂停控制台。如果我只使用1,程序在输入后结束。那么,为什么它需要2个readline方法而不是其他方法呢?有什么想法吗 请注意,在我的代码中,我已经注释掉了1个readline方法,这是我希望我的程序工作的方式,但它没有。然而,删除注释可以让程序工作,但我不明白为什么 using System; using System.Collections.Generic; using System.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoinFlip
{
class Program
{
static void Main(string[] args)
{
Random rng = new Random();
Console.WriteLine(@"
This program will allow you to guess heads or tails on a coin flip.
Please enter h for heads, or t for tails and press Enter: ");
char userGuess = (char)Console.Read();
int coin = rng.Next(0,2);
Console.WriteLine("Coin is {0}\n\n", coin);
if (coin == 0 && (userGuess == 'h' || userGuess == 'H'))
{
Console.WriteLine("It's heads! You win!");
}
else if (coin == 1 && (userGuess == 't' || userGuess == 'T'))
{
Console.WriteLine("It's tails! You win!");
}
else if (userGuess != 't' && userGuess != 'T' && userGuess != 'h' && userGuess != 'H')
{
Console.WriteLine("You didn't enter a valid letter");
}
else
{
if (coin == 0) { Console.WriteLine("You lose mofo. The coin was heads!"); }
if (coin == 1) { Console.WriteLine("You lose mofo. The coin was tails!"); }
}
Console.ReadLine();
//Console.ReadLine();
}
}
}
您使用的是
Console.Read()
,它在用户点击return后读取单个字符。但是,它只使用单个字符-这意味着行的其余部分(即使是空的)仍在等待使用。。。Console.ReadLine()正在执行的操作
最简单的解决方法是使用前面的Console.ReadLine()
:
string userGuess = Console.ReadLine();
。。然后检查猜测是否为单个字符,或者将所有字符文本(例如,'t'
)更改为字符串文本(例如,“t”
)
(或者按照Servy的建议使用
Console.ReadKey()
。这取决于您是否希望用户点击回车键。)简短的回答是,不要使用Console.Read。在您提交一行文本之前,它无法读取任何内容,但它只读取该行文本的第一个字符,将该行的其余部分留给进一步的控制台输入,例如调用console.ReadLine
。使用Console.ReadKey
而不是Console.Read
来读取单个字符。第一个控制台。ReadLine()被Enter键使用,因此程序结束。
请尝试此操作,而不要使用Console.Read()
var consoleKeyInfo = Console.ReadKey();
var userGuess = consoleKeyInfo.KeyChar;
还要注意行:Console.WriteLine(“Coin是{0}\n\n”,Coin);是为了让我自己能看到变量数。这将从最后的节目中删除。干杯,伙计们,哇,你们超快,解释得很好。根据您的解释,我在底部添加了以下代码来测试您所说的内容:Console.WriteLine(Console.ReadLine());Console.ReadLine();然后我写了《西红柿》,确信它用t表示尾巴,然后在控制台上读“omato”。WriteLineal于是我买了一本叫做《C#In depth第三版》的书,我打算在掌握了基本知识后再读。不确定你是不是写这篇文章的那个人。@user4202953:是的,我是。希望你喜欢:)哈哈,用最书呆子的方式,我只想说我的问题被一位畅销书作家回答了,真是太棒了。谢谢。:)谢谢你的回答。虽然我更明白乔恩的解释。您确实向我介绍了一个新方法*Console.ReadKey,我一定会使用它。谢谢。:)