helloworldztb97
helloworldztb97

Reputation: 33

.NET 5.0, Trying to sum user input in loop overwrites sum with user input value

The goal of this part of the program is to just keep asking the user to enter a number, and then sum that with all the previous numbers the user has entered. It will display the total summed every time the user enters a number. The user can break the loop by entering "ok" into the console instead of a number. However, the summed value I am printing to the console is equivalent to the inputValue every iteration through, which isn't the goal of this program.

How I interpret my code:

Inside the while loop, I ask the user to enter a number. This is initially stored into input as a string. From there we control the flow of the program through a conditional if statement. IF the string we have stored inside the input variable is == the string "ok" we will break our loop thus terminating the program.

If this condition is not met, we continue into the try {} block, where we will now convert our input representing a number (Ex: "32") to an int32, which we now store into inputTally. From there we are summing inputTally with the total of tally (initialized to 0), and assigning this to the tally variable. I will then write the value inside of tally to the console, showing the sum of all the numbers I've entered previously.

What actually happens:

The same as described above, with one key difference: When displaying the sum of my tally, the total is always the inputTally that I just entered. (Ex: if I were to enter 5 as my input five times, I would expect my tally to be 25. However, my tally is repeatedly just 5).

while (true)
{
    string input;
    int tally = 0;
    int inputTally;
    Console.Write("Enter a number: ");
    input = Console.ReadLine();
    if (input == "ok")
    {
        break;
    }
    else
    {
        try
        {
            inputTally = Convert.ToInt32(input);
            tally = tally + inputTally;
            Console.WriteLine($"Tally: {tally}");
        }
        catch
        {
            Console.WriteLine("For some reason I couldn't perform the required tasks. Maybe you didn't type ok or a string I can convert to int.");
        }
    }
}

Why do I not have the functionality I expect? What is causing this?

Upvotes: 0

Views: 313

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

Move the declaration of int tally = 0 so it is above the while. Currently you effectively initialize tally to 0 on every pass of the loop so it can never sum to a value greater than 0+what_the_user_just_entered

You might also want to consider switching to int.TryParse to do your conversion from string to int, rather than Convert.ToInt32; TryParse doesn't error on bad input, it just returns a boolean false if it wasn't able to convert the value, rather than raising an exception. Exceptions are expensive and we avoid code that raises them if we can

In this case you don't even need to inspect the returned boolean, because a failure to parse a value will place a 0 on the output integer (and adding 0 is a non op)

//you can change
inputTally = Convert.ToInt32(input);

//to
int.TryParse(input, out inputTally);

but if you did want to use the returned boolean e.g. to print a message about how the user should enter a numeric string, then you can


Side note, stepping through your program in the debugger would likely have led you to realize the problem; be sure to read up on how to make effective use of the debugging tools in visual studio- they really demystify what goes on when your program executes, and learning how to debug is probably the single biggest boost to productivity you'll discover as a developer

As the world's quickest tutorial on using it: click on the while line and press F9, ensure the project mode is Debug and press play; when the code stops with a yellow bar press F10 to advance a step at a time and point to variables with your mouse to see their current value. You can also step with F11, the difference being that F11 will call into methods, whereas F10 runs methods without going into them (you don't seem to have any debuggae methods here but one day you will have)

Upvotes: 3

Related Questions