2

I'm just learning c#, and I like to understand everything before I move on.

The problem I'm having is I need 2 Console.ReadLine(); to pause the console. If I just use 1, the program ends after the input. So why does it need 2 readline methods instead of? Any ideas?

Please note in my code, I've commented out 1 of the readline methods, the way I want my program to work but it doesn't. However removing the comments allows the program to work, but I don't understand why.

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();
        }
    }
}
4

3 回答 3

4

您正在使用,它在用户点击 return 后Console.Read()读取单个字符。但是,它只消耗那个单个字符 - 这意味着该行的其余部分(即使它是空的)仍在等待被消耗......这是在做的。Console.ReadLine()

最简单的解决方法是Console.ReadLine()更早地使用:

string userGuess = Console.ReadLine();

..然后可能检查猜测是单个字符,或者只是将所有字符文字(例如't')更改为字符串文字(例如"t")。

(或者Console.ReadKey()按照Servy的建议使用。这取决于您是否希望用户点击返回。)

于 2014-10-31T15:06:30.630 回答
3

简短的回答,不要使用Console.Read. 在您提交一行文本之前,它无法读取任何内容,但它只读取该文本行的第一个字符,将该行的其余部分留给进一步的控制台输入,例如,调用Console.ReadLine. 使用Console.ReadKey而不是Console.Read读取单个字符。

于 2014-10-31T15:07:21.377 回答
0

第一个Console.ReadLine()Enter键使用,因此程序结束。
试试这个而不是Console.Read()

    var consoleKeyInfo = Console.ReadKey();
    var userGuess = consoleKeyInfo.KeyChar;
于 2014-10-31T15:11:54.887 回答