user3029538
user3029538

Reputation: 15

How can I loop and check for correct user input in C#?

In this following main method I am trying to code so if the user does not input the proper response, then the code will loop until the user does provide the correct response.

I know I'm off center here, but I'm drawing a blank of how to correct this.

Please keep in mind I'm tying to keep this simple and basic.

public static void Main()
    {
        string name = "";
        float startBal = 0;
        int acctNum = 0;
        string userInput = "";
        float[] deposits = new float[30];
        float[] withdrawls = new float[30];

        DisplayIntroduction();
        name = GetName();
        startBal = GetStartBal();
        acctNum = CreateAccount();

        Console.WriteLine("\n{0}, here is your new account # {1}\n", name, acctNum);

        do
        {
            Console.Write("Enter a 'D' to Deposit, 'W' to Withdrawl, or 'X' to End the program: ");
            userInput = Convert.ToString(Console.ReadLine());

            if (userInput.ToUpper() == "D")
            {
                //do the deposit, modify the deposit array
                Console.WriteLine("You entered D");
            }
            else if (userInput.ToUpper() == "W")
            {
                //do the withdrawl, modify the withdrawl array
                Console.WriteLine("You entered W");
            }
            else if (userInput.ToUpper() == "X")
            {
                //end the program, clear screen and display the summary
                Console.WriteLine("You entered X");
            }
            else
            {
                Console.WriteLine("Please enter a valid option:");

            }
        } while (userInput.ToUpper != "D" || userInput.ToUpper != "W" || userInput.ToUpper != "X");


    }

Upvotes: 1

Views: 2319

Answers (5)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

My version is something like this:

// While loop usually read better: keep on asking again and again until 
// valid value is chosen
while (true) {
  Console.Write("Enter a 'D' to Deposit, 'W' to Withdrawl, or 'X' to End the program: ");
  String userInput = Console.ReadLine(); // <- You don't need any Convert here

  // Try not use ".ToUpper" - move it to comparison: StringComparison.OrdinalIgnoreCase
  if (String.Equals(userInput, "D", StringComparison.OrdinalIgnoreCase)) {
    Console.Write("You've entered 'D'");

    break;
  }
  else if (String.Equals(userInput, "W", StringComparison.OrdinalIgnoreCase)) {
    Console.Write("You've entered 'W'");

    break;
  }
  else if (String.Equals(userInput, "X", StringComparison.OrdinalIgnoreCase)) {
    Console.Write("You've entered 'X'");

    break;
  }

  Console.WriteLine();
  Console.WriteLine("You've written an invalid option.");
}

Upvotes: 0

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9191

Common mistake, it should be some AND operators in your while, not OR.

while (userInput.ToUpper != "D" && userInput.ToUpper != "W" && userInput.ToUpper != "X")

You want to loop if it's different than D AND different than W. Else it will always be true, since it cannot be D and W at the same time.

For example, if user inputs D, you get false true true, but you need a global result of false to leave the loop. With ANDs, you get a global result of false, while with OR you get true.

You can also use make it a little bit more compact (and less error-prone) with some LINQ (Works great for a lot of elements):

while(!new[] {"D", "W", "X"}.Contains(userInput));

Upvotes: 5

Haedrian
Haedrian

Reputation: 4328

The "while" condition means the loop will keep triggering until the statement is false.

(userInput.ToUpper != "D" || userInput.ToUpper != "W" || userInput.ToUpper != "X");

Is going to be looping forever.

If the user enters "D" for instance

false OR true OR true

true

You'll want an & instead

(userInput.ToUpper != "D" && userInput.ToUpper != "W" && userInput.ToUpper != "X");

If user enters a "D"

false AND true AND true = false

(break out)

If user enters a "Z"

true and true and true = true (remain in loop)

Upvotes: 0

Shaharyar
Shaharyar

Reputation: 12439

It is not efficient to check twice a thing, you are checking user input in if-statements and again in the while-condition.

The simplest way is to set up a bool type variable to indicate whether user has entered the correct response or not.

bool flag = false;
do{ 
//your code
}
while(!flag)

and add this in every if-statement:

flag = true;

indicating that the user has inputed the correct value.

Upvotes: 1

Augustus Francis
Augustus Francis

Reputation: 2670

Pierre-Luc Pineault is correct.. But more logically it would be best to do..

while(!(userInput.ToUpper == "D" || userInput.ToUpper == "W" || userInput.ToUpper == "X"))

Upvotes: 0

Related Questions