Getting the input from user till valid input received - c#

I am seeking input from user on console
cki = Console.ReadKey();
Console.WriteLine("");
string character = cki.KeyChar.ToString();
if (character == "1")
{
Console.WriteLine("Please wait...");
Name_Updater nu = new Name_Updater();
nu.Name_Update();
}
else if (character == "2")
{
Console.WriteLine("Please wait...");
WCM_Interaction wi = new WCM_Interaction();
wi.Interact_WCM();
}
else
{
Console.WriteLine("Invalid key! Please try again");
}
but it stops after one iteration, if user enters the invalid input. However I want it to accept inputs from the user till it receives the valid input, but I have confusion on where to place the loop.

cki = Console.ReadKey();
string character = cki.KeyChar.ToString();
while (true) // infinite loop
{
if (character == "1")
{
Console.WriteLine("Please wait...");
Name_Updater nu = new Name_Updater();
nu.Name_Update();
break; // break from loop if you read "1"
}
if (character == "2")
{
Console.WriteLine("Please wait...");
WCM_Interaction wi = new WCM_Interaction();
wi.Interact_WCM();
break; // break from loop if you read "2"
}
// repeat loop if invalid entery
Console.WriteLine("Invalid key! Please try again");
cki = Console.ReadKey();
character = cki.KeyChar.ToString();
}

bool correctInput = false;
while (!correctInput)
{
correctInput = true;
string decision = Console.ReadLine();
int iDecision;
if (int.TryParse(decision, out iDecision))
switch (iDecision)
{
case 0:
// do something
break;
case 1:
// do something else
break;
default:
correctInput = false;
break;
}
else
correctInput = false;
if (!correctInput)
Console.WriteLine("Tell user their input was bad.");
}

You can place a do while loop to make iterations. It can be embedded as:
cki = Console.ReadKey();
Console.WriteLine("");
string character;
bool flag=true;
do
{
character = cki.KeyChar.ToString();
if (character == "1")
{
Console.WriteLine("Please wait...");
Name_Updater nu = new Name_Updater();
nu.Name_Update();
flag=false;
}
else if (character == "2")
{
Console.WriteLine("Please wait...");
WCM_Interaction wi = new WCM_Interaction();
wi.Interact_WCM();
flag=false;
}
else
{
Console.WriteLine("Invalid key! Please try again");
}
}while(flag)

You can do it like this, what it does is you create a flag, and then set it to true once you satisfy your condition.
bool isValid = false;
while (!isValid)
{
var cki = Console.ReadKey();
Console.WriteLine("");
string character = cki.KeyChar.ToString();
if (character == "1")
{
Console.WriteLine("Please wait...");
//Name_Updater nu = new Name_Updater();
//nu.Name_Update();
isValid = true;
}
else if (character == "2")
{
Console.WriteLine("Please wait...");
//WCM_Interaction wi = new WCM_Interaction();
//wi.Interact_WCM();
isValid = true;
}
else
{
Console.WriteLine("Invalid key! Please try again");
}
}

Related

Wait for user to input specific number of commands before proceeding to process the business logic?

I am creating an application that wait's for the user to input a command.
I need n #'s of command from the user before I proceed to process the business logic.
string GetInputCommand()
{
var response = string.Empty;
var num = 0;
while (true)
{
response = Console.ReadLine().ToUpper();
if (validCommand.Contains(response.ToUpper().Substring(0, 1)) && response.ToUpper().Substring(0, 1) == "W")
{
if (isValidWinningCommand(response))
break;
else if (response.Length >= 3)
Console.WriteLine("Invalid Horse Number: {0}", response.Substring(2));
else
Console.WriteLine("Please Enter Horse Number");
}
else if (int.TryParse(response.ToUpper().Substring(0, 1), out num))
{
if (num >= 1 && num <= 7)
{
if (isValidWagerCommand(response))
break;
else if (response.Length >= 3)
Console.WriteLine("Invalid Bet: {0}", response.Substring(2));
else
Console.WriteLine("Please Enter Bet Amount");
}
else
Console.WriteLine("Invalid Command: {0}", response);
}
else if (validCommand.Contains(response))
{
break;
}
else
Console.WriteLine("Invalid Command: {0}", response);
}
return response;
}
This is how I'm calling the GetInputCommand
var command = p.GetInputCommand();
foreach (string cmd in command)
{
//logic to process all the command 1 once.
}

How to use loops instead of goto statement

I'm new to C# and want to implement loops , right now I'm using goto statement and labels but I have read that it is not suggested to use goto statement
so i was thinking to implement loops instead of goto and labels , byt i dont know how can i replace goto with loops
and if possible please also give a small explanation of the answer
here is my code with goto and labels
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
int TotalCoffeeCost = 0;
// Start is a lable to point to this location so i can use it in goto
Start:
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
TotalCoffeeCost += 2;
break;
case 2:
TotalCoffeeCost += 5;
break;
case 3:
TotalCoffeeCost += 7;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a vaild choice");
goto Start;
}
// YesOrNo is a lable to point to this location so i can use it in goto
YesOrNo:
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
goto Start;
}else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
goto LastConfirmation;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a vailed choice");
goto YesOrNo;
}
// LastConfirmation is a lable to point to this location so i can use it in goto
LastConfirmation:
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if(UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
goto Amount;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
goto Start;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a vaild choice");
goto LastConfirmation;
}
// Amount is a lable to point to this location so i can use it in goto
Amount:
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if(EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
goto Amount;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}
}
Just use while loops and methods to make this work.
Your Start method could look like this:
public void Start(int TotalCoffeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, - large");
Console.Write(" ");
int CoffeChoice = 0;
do
{
CoffeChoice = int.Parse(Console.ReadLine());//Asking for Choice until you put in 1,2 or 3
}while(CoffeChoice != 1 | CoffeChoice != 2 | CoffeChoice != 3)
switch (CoffeeChoice)
{
case 1:
TotalCoffeeCost += 2;
break;
case 2:
TotalCoffeeCost += 5;
break;
case 3:
TotalCoffeeCost += 7;
break;
}
}
And you can call the method like this:
public static void Main()
{
int TotalCoffeeCost = 0;
Start(TotalCoffeCost);
}
We can use methods and a simple bool "lock" that either keeps you inside the while loop, or breaks out of it when conditions are met:
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
var exiting = false;
while (!exiting)
{
programLoop();
}
}
private int askForCoffee()
{
int totalCoffeeCost = 0;
bool invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
return totalCoffeeCost;
}
private void programLoop()
{
int TotalCoffeeCost = 0;
TotalCoffeeCost += askForCoffee();
var invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
TotalCoffeeCost += askForCoffee(); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if(UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if(EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}

How to make the console accept input from the Enter key only?

I'd like to make the C# console only accept input from the Enter key on the startup screen.
I've made it so that it closes the console when anything but the Enter key is pressed.
How can I make it so that the console only accepts input from the Enter key so that the application doesn't close when I press anything else, and then receive normal input afterwards?
class Program
{
public static void ClearKeyBuffer()
{
while (Console.KeyAvailable)
Console.ReadKey(true);
}
public static void Main (string[] args)
{
int attempts = 0;
int displayattempts = 5;
bool validentry;
Console.WriteLine("Please press enter to begin");
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
while (attempts < 5)
{
string input;
attempts = (attempts + 1);
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
Console.Clear();
Console.WriteLine("Please enter your user number.");
Console.WriteLine("Attempts Remaining:" + displayattempts);
ClearKeyBuffer();
Console.WriteLine(" ");
input = Console.ReadLine();
{
if (input == "5573")
{
validentry = true;
}
else
{
validentry = false;
}
if (validentry == false)
{
displayattempts = (displayattempts - 1);
Console.Clear();
Console.WriteLine("Error: Invalid number ID entered. Please wait 5
seconds, and try again.");
Thread.Sleep(5000);
}
else if (validentry == true)
{
Console.Clear();
Console.WriteLine("Welcome Samuel");
ValidUserEntry();
}
}
}
}
if (displayattempts == 0)
{
Console.Clear();
Console.WriteLine("Error: You have entered the wrong number ID too many times.
This system will now close in 5 seconds...");
Thread.Sleep(5000);
Environment.Exit(0);
}
}
public static void ValidUserEntry()
{
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("What would you like to do?");
Console.ReadLine();
}
}
Add this line before first if. Then remove if statement and the var key... line.
while (Console.ReadKey(true).Key != ConsoleKey.Enter);
Alternative, more verbose version:
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
} while (key.Key != ConsoleKey.Enter);

How to ask until the user get specific reply in C#

{
bool stayInLoop = true;
while(stayInLoop)
{
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
}
I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)
You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
switch(exp)
{
case "+":
{
var sum = 0;
for(;;)
{
Console.WriteLine("Enter Yor Number");
var line = Console.ReadLine();
if (line == ";") break;
sum += Convert.ToInt32(line);
}
Console.WriteLine(sum);
break;
}
}
Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.
Use a while loop:
switch(exp)
{
case "+":
int sum = 0;
string input = "";
do
{
Console.WriteLine("Enter your number:");
input = Console.ReadLine();
if (input != ";")
sum += int.Parse(input);
} while (input != ";");
Console.WriteLine("Answer =" + sum);
break;
}
You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
case "+":
int mySum = 0;
string userInput = "";
while(userInput != ";")
{
Console.WriteLine("Enter number to add (';' to end the sum):");
userInput = Console.ReadLine();
if (userInput != ";")
{
// Would be interesting checking if entered really is an integer, for example Int32.TyParse()
mySum = mySum + Convert.ToInt32(userInput);
}
}
Console.WriteLine("Answer =" + mySum.ToString());
break;
}
Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
bool stayInLoop = true;
while(stayInLoop)
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
and when I run this, it run out 'error CS0019' and 'error CS0139'
What you're looking for is a while() loop.
example:
bool stayInLoop = true;
while(stayInLoop) // basically means (stayInLoop == true)
{
var text = Console.ReadLine();
if(text == ';')
{
stayInLoop = false;
break; // break will stop the loop, but you can also change the variable to false to break the loop.
}
}

How to make number Count in loop in c#?

This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}

Categories

Resources