0

For this problem, I am attempting to have Console messages displayed whenever a user inputs a choice between 0-2. But whenever I get to the case, the associated Console messages won't display and neither will the Console message at the end. Adding a default didn't work, and there doesn't seem to be anything else I could do to fix it alone. Any suggestions on what to do and what the problem is?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading.Tasks;

namespace Practice_actual
{
  
    internal class Program
    {  public static void Main(string[] args)
        { 
            Console.WriteLine("Please pick your choice 1-3");
            string answer=Console.ReadLine();
            int choice=Int32.Parse(answer);
            switch(choice)
            {
                    case 0:
                    Console.WriteLine("You chose 1");
                    break;
                    case 1:
                    Console.WriteLine("You chose 2");
                    break ;
                    case 2:
                    Console.WriteLine("You chose 3");
                    break;
                    default:
                    Console.WriteLine("Default option");
                    break;

            }
            Console.WriteLine("we have exited the switch structure");
        }
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • By the way, I also tried rebuilding the program in case of a error I didn't know about. – Brandon Rogers Sep 16 '22 at 20:26
  • Works for me. Note, when you use `ReadLine()` you have to press enter for the input to be processed. On another note, it's a bit confusing when I enter 2 and it says 'You chose 3', _no I entered 2 not 3~_. – quaabaam Sep 16 '22 at 20:32
  • You code works just fine. The application will immediately end as soon as the answer is printed. Try adding a `Console.ReadKey()` at the end. – Paul Sinnema Sep 16 '22 at 20:33
  • 1
    Does the console stay open? If not, are you creating a Framework 4.x project? – CodeCaster Sep 16 '22 at 20:38
  • It does stay open. And honestly, I'm so new to programming I only know I'm creating a C# NET framework. – Brandon Rogers Sep 16 '22 at 20:44
  • @quaabaam, that was a minor syntax error I discovered upon implementing my fix. Apologies! – Brandon Rogers Sep 16 '22 at 20:46
  • You will probably be **MUCH** happier if you get rid of this line `int choice=Int32.Parse(answer);`, make the `switch` switch on `answer` rather than `choice`, and then have the cases use strings like: `case "0":`. That way, if someone types `"foo"` instead of `"0"` you will fall into the default case (instead of throwing an exception on the call to `int.Parse`) – Flydog57 Sep 16 '22 at 21:22

1 Answers1

1

Just add a Console.ReadLine() or Console.ReadKey() at the end to freeze the command window till you enter something

WisdomSeeker
  • 854
  • 6
  • 8