Haydan Schweinhund Haydan Schweinhund - 1 month ago 7
C# Question

Application Not Working Correctly C#

My code isn't storing a response as user input. It jumps to the else statement every time I get here. Then it throws the sum as 50? When I store input like Value of first number = 2 and value of second = 3.
I'm doing a class at home and I have been working for a few hours trying to figure out why my code doesn't work right.
C#, below:

Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
bool stopOrContinueAdding = true;
do
{
string inputMoreNumbers = Console.ReadLine();
switch (inputMoreNumbers.ToLower())
{
case "a":
inputMoreNumbers = "a";
stopOrContinueAdding = false;
break;
case "b":
inputMoreNumbers = "b";
stopOrContinueAdding = true;
break;
default:
stopOrContinueAdding = false;
break;
}
if (stopOrContinueAdding == false)
{
int sum = aNum.Sum();
Console.WriteLine("Here is the sum of your numbers: " + sum );
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Redirecting to main menu...");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Console.Write("Addition(a), Subraction(s), Multiplication(x), or Division(d)? ");
isInputValid = false;
}
else
{
Console.Clear();
Console.Write("Value of next number: ");
number++;
aNum[number - 1] = Convert.ToInt32(Console.Read());
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
}
} while (stopOrContinueAdding != true) ;


I'm not entirely sure where I went wrong. I'd like to understand more :(

Thanks!

Answer

In your addition calculator, changing the following line:

aNum[number - 1] = Convert.ToInt32(Console.Read());

from Console.Read() to Console.ReadLine() seems to fix the issue. ReadLine() will block the execution until Enter is hit - Read() will not... So when you enter your second number and hit Enter, it executes your next ReadLine() statement (where you are expecting "a" or "b" depending on whether they want to continue) as a blank string.

Comments