mercredi 5 septembre 2018

Asking the user the same question more than once in C#

Starting my Intro To Programming class and we'll be using C# throughout it. I'm currently writing a practice program to get familiar with C# that asks the user for their name and age and then reads it out to them and asks if it is correct. I want to make it so that if the user wants to change their inputted data for any reason then they can press the "n" key for "no that's not right" and re enter their data. However, I want to re-ask them the questions for their age and name(separately) without having to re-type the code block with the Console.WriteLines and if...else block. I did some research and found that:

  1. the "go-to" statement was made by the devil himself and it's essentially the programming equivalent of a hate crime if I use it
  2. making a new method (and subsequently calling that method in my code) with the block of code asking the question seems to be the way to go about it.

My problem is that while I've (hopefully) figured out that's what I need to do, I can't seem to figure out how exactly to either implement that method nor call it correctly later on.

here is the method I'm trying to create that I want to hold an "if...else" statement asking if the info is correct, incorrect, or re-ask the question if the enter something other than "y" or "n":

public void Question()
            {
        Console.Write("Could I get your name? (Press enter when you are done) ");
        string user_name = Console.ReadLine();
        Console.Clear();
        Console.Write("Awesome! Now if you could just enter your age: ");
        string user_age = Console.ReadLine();
        Console.Clear();
        Console.WriteLine("So according to the information I have on file here... you are " + user_name + " and you're " + user_age + " years old....");

    }

This isn't homework so I don't mind specific pieces of code so I can see how it works and tinker with it to learn :)

Aucun commentaire:

Enregistrer un commentaire