Receiving Input, Printing Output

2718 views c#
3

I've just started to learn some actual OOP. This will be my first week programming so I figured I could try and create a basic game within CMD prompt. I'm trying to give the player a choice between two things. As of right now the program just asks "Are you ready to begin your adventure". Everything is working as intended until It gets to the choices portion. After inputting an answer the CMD prompt just goes to the next line without saying anything and exits. Any suggestions as to what I did wrong would be greatly appreciated.

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

namespace InteractiveGame
{
    class Program
    {
        static void Main(string[] args)
        {

        string CharName = "John Doe";
        string InvalidInput = "This is an invalid answer, please choose a 
        correct option";
        string GameOver = "You Died, Game Over";







        Console.WriteLine("Welcome to Dragon Land!");
        Console.WriteLine("What is your name young traveler?");
        CharName = Console.ReadLine();

        Console.WriteLine("Are you ready to begin your adventure " + 
        CharName + "?");
        Console.WriteLine("Y/N?");
        Console.ReadLine();

        var answer = Console.Read();
        if (answer == 'Y' || answer =='y')
        {
            Console.WriteLine("You begin your journey!");
        }
        if (answer == 'N' || answer == 'n')
        {
                Console.WriteLine(GameOver);
            }
            else
            {
                Console.WriteLine(InvalidInput);
            }
            Console.ReadLine();
        }
    }
}

answered question

1 Answer

10

Your problem is here:

Console.ReadLine();
var answer = Console.Read();

You are discarding the first answer the user is giving you. You should be doing:

var answer = Console.ReadLine();

Also, your app is going to behave weird if the user inputs anything other than "Y", "y", "N" or "n". What do you want your program to do if the user inputs "D"? You'll probably want the user to try again won't you? How can you achieve that with your current setting? Seems hard...

When building these type of cmd apps there are some tools you should get familiar with:

  1. if-elseif-else statements
  2. do-while loops (really handy)
  3. Extracting common functionality to helper methods (maybe asking the user for a choice always follows a pattern; why write the same code 100 times when you can write one method you can call again and again?)

posted this

Have an answer?

JD

Please login first before posting an answer.