Ulises Sanchez
Ulises Sanchez

Reputation: 1

How do I make the program request user input after inputting invalid data in C#?

I am not sure how to tackle this problem. I tried putting the do while loop in the method GetUserInput and then putting the for loop in the do while loop. It doesn't reset the question it just takes the number and adds it the numbers before it. Its a supposed to be a calculator program.

//This propgram will be used to make a calculator for the class project.
//The numbers are stored as floats as well as the result. Then displayed on console.
//V1 adds a do-while loop that repeats as long as the user wants.
//V2 adds a if and else logic for when the user input a character other than a number the program will close.
//V3 added a for-loop to increase the amount of numbers that can be considered in the calculation. It makes an array
//V4 added methods to get user input and sum the numbers

class MainClass
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello Ulises Sanchez");
        //Define 3 floating point numbers to capture the 2 inputs and the result
        //floats are used to capture a broader range of numbers
        float[] userInput = new float[10];

        //stores the number of inputs the user requests
        int numberOfUserInputs;

        //define strings to store data read and also user prompts
        string inputString;
        string doMorefunctions = "Add More Numbers Together - y = yes - anything else for no";

        //variable to test the condition to continue with calculations
        bool moreActions;

        do
        {
            Console.Clear();
            numberOfUserInputs = GetuserInput(userInput);

            //adds the numbers together
            Summation(userInput, numberOfUserInputs);

            //reset moreAction
            moreActions = false;
            Console.WriteLine(doMorefunctions);
            inputString = Console.ReadLine();
            if (inputString == "y" || inputString == "Y") 
                moreActions = true;
        } while (moreActions);
    }

    //Gets the number of user inputs and stores each in the userInput array
    static int GetuserInput(float[] inputArray)
    {
        int numberOfInputs;
        string userInputPrompt = "How many numbers do you want to enter?";

        //string continueMessage = "Hit any key to continue";
        string errorMessage = "Invalid Input";
        string inputString;
        bool TryAgain;
        Array.Clear(inputArray, 0, 10);

        //Gets number of inputs from user
        Console.Write(userInputPrompt);
        inputString = Console.ReadLine();
        numberOfInputs = int.Parse(inputString);

        //Get inputs
        for (int i = 0; i < numberOfInputs; i++)
        {
            Console.Write("Enter variable number {0}: ", i + 1);
            inputString = Console.ReadLine();

            if (Single.TryParse(inputString, out float result))
            {
                //if input is valid convert to float
                inputArray[i] = float.Parse(inputString);
            }
            else
            {
                TryAgain = false;
                Console.WriteLine(errorMessage);
                inputString = Console.ReadLine();
                if (inputString == "y" || inputString == "Y") TryAgain = true;
                //if input is not valid input exit program
                //Console.WriteLine(continueMessage);
                //Console.ReadLine();
                //System.Environment.Exit(1);
            }
        }
        return numberOfInputs;          
    }

    //takes the user input and performs a summation calculation
    static void Summation(float[] inputArray, int numberOfInputs)
    {
        float summationResult = 0.0f;
        for (int i = 0; i < numberOfInputs; i++)
        {
            summationResult += inputArray[i];
        }

        //display result to the screen
        Console.WriteLine("Summation = {0}", summationResult);              
    }   
}

Upvotes: 0

Views: 99

Answers (1)

Caius Jard
Caius Jard

Reputation: 74660

We have this concept of "don't repeat yourself" (DRY) so we look for ways to make code that repeats itself not do so. Every one of your methods repeats the print/ReadLine process for asking a question

Let's have a method that asks the user for a string:

public string Ask(string q){
  Console.WriteLine(q);
  return Console.ReadLine();
}

Now we can say:

string name = Ask("what is your name? ");

Suppose blank input is invalid, let's use a loop to repeat the question:

public string Ask(string q){
  string a = "";
  while(string.IsNullOrEmpty(a)){
    Console.WriteLine(q);
    a = Console.ReadLine();
  }
  return a;
}

If the user gives no answer, they are stuck in the loop and the question is repeated until they give a valid answer

Now let's reuse this to ask for an int:

public int AskInt(string q){
  return int.Parse(Ask(q));
}

Here we reuse Ask within AskInt so we don't do the print/read thing again and we leverage the "cannot renter blank" validation we already write

This however explodes if the user enters non ints

So let's use int.TryParse and keep looping while they enter garbage that doesn't parse;

public int AskInt(string q){
  bool success = false;
  into a=0;
  while(!success){
    success = int.TryParse(Ask(q), out a);
  }
  return a;
}

The user can only get to the last line if they enter an int

If you also want to add range validation, for example, you can put an int min, int max into your method parameters and inside the loop do success = success && a <= && a >= min

int guess = AskInt("enter a number between 1 and 10: ", 1, 10);

The idea is to write one method that does one thing really well I.e. "ask the user for a string" and then reuse that when we write the next method that does one thing well, so we end up with two methods that do two things well. Giving the methods a sensible name allows us to package up that bit of logic they do into a few words and make out code read like a book. It doesn't need as many comments then

//ask the user what their next guess is
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);

This comment isn't needed; we can easily deduce the same just by reading the code.

Upvotes: 3

Related Questions