Friday 15 August 2014

c# - Why do I need 2 Console.ReadLine(); to pause the console? -



c# - Why do I need 2 Console.ReadLine(); to pause the console? -

i'm learning c#, , understand before move on.

the problem i'm having need 2 console.readline(); pause console. if utilize 1, programme ends after input. why need 2 readline methods instead of? ideas?

please note in code, i've commented out 1 of readline methods, way want programme work doesn't. removing comments allows programme work, don't understand why.

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace coinflip { class programme { static void main(string[] args) { random rng = new random(); console.writeline(@" programme allow guess heads or tails on coin flip. please come in h heads, or t tails , press enter: "); char userguess = (char)console.read(); int coin = rng.next(0,2); console.writeline("coin {0}\n\n", coin); if (coin == 0 && (userguess == 'h' || userguess == 'h')) { console.writeline("it's heads! win!"); } else if (coin == 1 && (userguess == 't' || userguess == 't')) { console.writeline("it's tails! win!"); } else if (userguess != 't' && userguess != 't' && userguess != 'h' && userguess != 'h') { console.writeline("you dumb mofo, didn't come in valid letter"); } else { if (coin == 0) { console.writeline("you lose mofo. coin heads!"); } if (coin == 1) { console.writeline("you lose mofo. coin tails!"); } } console.readline(); //console.readline(); } } }

you're using console.read(), reads single character after user has nail return. however, consumes single character - means rest of line (even if it's empty) still waiting consumed... console.readline() doing.

the simplest prepare utilize console.readline() before too:

string userguess = console.readline();

.. maybe check guess single character, or alter character literals (e.g. 't') string literals (e.g. "t").

(or utilize console.readkey() servy suggested. depends on whether want user nail homecoming or not.)

c# console.readline

No comments:

Post a Comment