makertech81
makertech81

Reputation: 928

Why does the console close after I type yes?

I was making a calculator in C#. Here is the multiplication part---

using System;
static class calculator 
{
    public static void Main() 
    {
    welcome:
    Console.WriteLine("Welcome to my calculator, please press enter to         continue");
    Console.ReadLine();
    Console.WriteLine("Do you want to add, subtract, multiply or divide?");
    string x = Convert.ToString(Console.ReadLine());
    if (x == "multiply") 
    {
        Console.WriteLine("Please enter the first value");
        decimal value1multiply = Convert.ToDecimal( Console.ReadLine());
        Console.WriteLine("Please enter the second value" );
        decimal value2multiply = Convert.ToDecimal(Console.ReadLine());
        Console.WriteLine("Result =");
        Console.WriteLine(value1multiply * value2multiply);
        Console.WriteLine("Thank you for using my calculator!Do you still want to use it?Please answer in 'yes' or 'no' and press 'enter'");
        Console.ReadLine();
        string yesorno =Console.ReadLine();
        if (yesorno == "yes") 
        {
            goto welcome;
        }
         if (yesorno == "no") 
         {
            Environment.Exit(0);
        }
    }
         }
       }

When I type 'yes' when it asks me to, the console should lead me to welcome. But instead, it does not lead me anywhere and remains blank. When I press enter again, the console closes. Why is this happening and how can I prevent it?

What I have tried:

I tried removing the environment.exit(0), thinking that the console was leading me to that but it did not help. I even tried typing the code in Visual Studio, but no difference in the outcome. (I use sharp develop)

Upvotes: 0

Views: 161

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157048

Besides the use of goto, which is often frowned upon, you are using one too much ReadLine call.

Here:

Console.ReadLine();
string yesorno = Console.ReadLine();

Maybe you typed yes and then hit Enter twice. In that case yesorno would be empty and your check would fail. The first entry is swallowed by the first ReadLine that didn't got assigned to a variable.

Upvotes: 7

Related Questions