❔ Practicing Arrays
Console.Write("How many numbers do you want?: "); int numberChoice = Console.Read(); if (numberChoice == 2) { Console.WriteLine("Which numbers are they?"); int numPick1 = Console.Read(); int numPick2 = Console.Read(); } else { Environment.Exit(0); }Hi! I enter 2 when prompted for numberChoice. It exits instead of going to if. What am I doing wrong?
12 Replies
Console.Read()
gives you a char
When converted to an int
, it gives the character's index on the ASCII tableAngius#1586
REPL Result: Success
Result: int
Compile: 343.747ms | Execution: 24.177ms | React with ❌ to remove this embed.
You want to check if the input is
'2'
not 2
Alternatively, you can use char.GetNumericValue()
Angius#1586
REPL Result: Success
Result: double
Compile: 445.800ms | Execution: 24.507ms | React with ❌ to remove this embed.
Oh! That makes a lot of sense, thank you. I changed it to '2' and it executed WriteLine, but I noticed numPick1 and numPick2 don't execute.
Sorry for the immediately follow up. I sat on this for a good minute 😓
How can you tell they "didn't execute"?
It immediately proceeds to exit after WriteLine
https://prnt.sc/KyhP_W-H8PeV
I don't know how to do those nice blocks on discord. Here's a better picture
https://prnt.sc/H93lsJ9xFUXz
Using Step Into during debug, it acknowledges the statements for my numPick vars, but it doesn't let me type in. Just goes right over them.
I tried to be creative and declare them outside the if statement... I knew that wouldn't work 😅
I'd say try
Console.ReadLine()
instead
It gives you a string?
so you'll need to int.TryParse()
or at least int.Parse()
it to a number
Or just compare it directly as a string if that's all you needComparing directly to a string definitely works. Though, I feel a little lazy doing it like that lol. But this helps for my practice purposes. Thank you! 😄
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.