[Solved] Why does int seem to default to 50 rather than 0 in C#?


It’s not printing 50 more times; it’s printing exactly 48 more times.

You’re reading a character and assigning its unicode value to an integer. For example, user types ‘1’, the character 1. Its Unicode value is 49. You assign 49 to your int print, and there you are. A character is really a small or smallish integer, which is essentially an index into a table of characters somewhere.

In Unicode, as in ASCII, ‘0’ is decimal 48, ‘1’ is decimal 49, and so on in order up to ‘9’. That’s where the 48 is coming from.

What you want to do is something more like this. First, you want to read the whole line, not just the first character; what if the user types “12”? Then you need parse the string “1” (or “12”, which is two characters) to get the integer ‘1’ or ’12’.

And in fact, that’s just what you did on this line:

print = Convert.ToInt32(Console.ReadLine());

So use that version every place that you’ve got print = Console.Read();

Second bug: You set print to some presumably small number, say the user types “4” so it’s 4. Then you loop while it’s greater than 10 — but it’s never greater than 10. You want to loop while it’s greater than zero:

while (print > 0)
{
    Console.WriteLine(cocaCola);
    print -= 1;
}

You need to fix that in three places.

Update

Three places is more than you want to deal with. So here’s another thing: You could simplify this code quite a bit by just setting a variable in the switch statement, and writing the loop only once (you could simplify it further in other ways, but let’s take one step at a time):

Console.WriteLine("Would you like to print picture 1, 2, or 3?");

int print = 0;
string choice = "";


while (choice != "end")
{
    choice = Console.ReadLine().Trim();
    String thingToPrint = null;

    switch (choice)
    {
        case "1":
            thingToPrint = cocaCola;
            break;

        case "2":
            thingToPrint = beam;
            break;

        case "3":
            thingToPrint = liberty;
            break;
    }

    if (thingToPrint != null)
    {
        Console.WriteLine("How many times would you like to print it");
        print = Convert.ToInt32(Console.ReadLine());
        while (print > 0)
        {
            Console.WriteLine(thingToPrint);
            print -= 1;
        }
    }
    else
    {
        Console.WriteLine("You chose poorly. Try again.");
    }

    Console.WriteLine("Choose again, or type \"end\" to exit");
}

6

solved Why does int seem to default to 50 rather than 0 in C#?