I'm trying to determine the best way to get the following code to iterate until the user enters a valid number(1-6). As long as the user inputs a number that is greater than 6, the program should continue to prompt the user for a valid number.
static void Main(string[] args)
{
string favoriteBand;
Console.WriteLine("What is your favorite rock band?");
Console.WriteLine("");
Console.WriteLine("1.) Journey");
Console.WriteLine("2.) Boston");
Console.WriteLine("3.) Styx");
Console.WriteLine("4.) Kansas");
Console.WriteLine("5.) Foreigner");
Console.WriteLine("Press 6 to exit the program.");
Console.WriteLine("");
favoriteBand = (Console.ReadLine());
switch (favoriteBand)
{
case "1": Console.WriteLine("Don't Stop Believin'!"); break;
case "2": Console.WriteLine("More Than a Feeling!"); break;
case "3": Console.WriteLine("Come Sail Away!"); break;
case "4": Console.WriteLine("Dust in the Wind!"); break;
case "5": Console.WriteLine("Hot Blooded!"); break;
case "6": return;
default: Console.WriteLine("Error, invalid choice. Please choose a valid number."); break;
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
How can I get this program to continue prompting for a valid number using a loop?
Just for fun, here we can remove the switch
(not really needed for a simple switch with only 6 cases)
bool isValid = true;
Dictionary<string, Action> command = new Dictionary<string, Action>();
command.Add("1", () => {Console.WriteLine("Don't Stop Believin'!");isValid = false;});
command.Add("2", () => {Console.WriteLine("More Than a Feeling!");isValid = false;});
command.Add("3", () => {Console.WriteLine("Come Sail Away!");isValid = false;});
command.Add("4", () => {Console.WriteLine("Dust in the Wind!");isValid = false;});
command.Add("5", () => {Console.WriteLine("Hot Blooded!");isValid = false;});
command.Add("6", () => isValid = false);
while(isValid)
{
string line = Console.ReadLine();
if(command.Keys.Contains(line))
command[line].Invoke();
else
Console.WriteLine("Choose from 1 to 6");
}
Use a bool variable with while
bool control = true;
while(control)
{
favoriteBand = (Console.ReadLine());
switch (favoriteBand)
{
case "1": Console.WriteLine("Don't Stop Believin'!"); control = false;break;
case "2": Console.WriteLine("More Than a Feeling!");control = false; break;
case "3": Console.WriteLine("Come Sail Away!"); control = false;break;
case "4": Console.WriteLine("Dust in the Wind!"); control = false;break;
case "5": Console.WriteLine("Hot Blooded!"); control = false;break;
case "6": control = false; break;
default: Console.WriteLine("Error, invalid choice. Please choose a valid number."); break;
}
}
Related
I'm trying to make a question repeat if the input isn't right. Here's the code:
Console.WriteLine("choose a name");
string userInput = Console.ReadLine();
Boolean input = true;
switch (userInput)
{
case "joe":
Console.WriteLine("you chose a joe");
break;
case "bob":
Console.WriteLine("you chose a bob");
break;
}
How do I make it if it isn't one of the two answers it reasks the question?
Use the default case.
If none of the cases in a switch statement match, the default case runs.
Here's an example.
Console.WriteLine("choose a name");
string userInput = Console.ReadLine();
switch (userInput)
{
case "joe":
// ...
break;
case "bob":
// ...
break;
default:
// This runs if userInput is neither "joe" nor "bob"
}
Then you can make a method that writes choose a name to the console, takes the user's input, and runs the switch statement - and the default case would call the same method.
void GetName()
{
// Write "choose a name" to the console
// Take the user's input
switch (userInput)
{
case "joe":
// ...
break;
case "bob":
// ...
break;
default:
GetName();
return;
}
}
You need a loop (either while or do-while) to repeat the iteration but not a switch-case.
While switch-case is used to control the flag (isCorrectInput) that stops the loop.
bool isCorrectInput = false;
do
{
Console.WriteLine("choose a name");
string userInput = Console.ReadLine();
switch (userInput)
{
case "joe":
Console.WriteLine("you chose a joe");
isCorrectInput = true;
break;
case "bob":
Console.WriteLine("you chose a bob");
isCorrectInput = true;
break;
}
} while (!isCorrectInput);
Reference
Iteration statement
You should use a bool variable, that will determine whether you need to repeat the logic or not. Combine it with a loop and you get this:
bool keepAsking = true;
while (keepAsking)
{
Console.WriteLine("choose a name");
string userInput = Console.ReadLine();
Boolean input = true;
switch (userInput)
{
case "joe":
Console.WriteLine("you chose a joe");
keepAsking = false;
break;
case "bob":
Console.WriteLine("you chose a bob");
keepAsking= false;
break;
}
}
You can try something like this. BUt you need to slightly change your code.
class XYZ
{
static void Main(string[] args)
{
GetData()
}
}
static void GetData()
{
string userInput = Console.ReadLine();
checkcondition(userInput);
}
static void checkcondition(userInput)
{
switch (userInput)
{
case "joe":
Console.WriteLine("you chose a joe");
break;
case "bob":
Console.WriteLine("you chose a bob");
break;
default:
GetData();
break;
}
}
You can also achieve the same results using a smaller code but with a while loop instead of switch statement
while(true){
Console.Write("Choose a Name: ");
var name = Console.ReadLine().ToLower();
if(name == "joe" || name == "bob"){
Console.WriteLine("You chose a " + name + "!");
break;
}else{
Console.WriteLine("Invalid Selection, Try Again");
}
}
I'm working a little with switch statements and want to know how to ignore the case sensitivity when it comes to input values.
Here is my code:
using System;
namespace SwitchStatements
{
class MainClass
{
public static void Main(string[] args)
{
Start:
Console.WriteLine("Please Input the Grade");
char grade = Convert.ToChar(Console.ReadLine());
switch (grade)
{
case 'A':
Console.WriteLine("Excellent Work!");
break;
case 'B':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
break;
}
Console.ReadKey();
goto Start;
}
}
}
If I put 'a' in instead of 'A' it returns the default response.
Can I use perhaps a .Comparison of some sort? If so where would I put it?
You can use ConsoleKey as condition for switch, the code will be like the following.
var grade =Console.ReadKey().Key;
switch (grade)
{
case ConsoleKey.A:
Console.WriteLine("Excellent Work!");
break;
case ConsoleKey.B:
// Something here
break;
case ConsoleKey.C:
// Something here
break;
case ConsoleKey.D:
// Something here
break;
case ConsoleKey.E:
// Something here
break;
default:
// Something here
break;
}
So that you can avoid converting the input to uppercase/Lower case, and then it goes for another conversion To Char. Simply use ConsoleKey Enumeration inside the switch.
You can use ToUpper(); Like
Convert.ToChar(Console.ReadLine().ToUpper());
and to get saved from the error of getting more charaters with Console.ReadLine() you can use
char grd = Convert.ToChar(Console.ReadKey().KeyChar.ToString().ToUpper());
you can use like following also
char grade = Convert.ToChar(Console.ReadLine().ToUpperInvariant());
https://msdn.microsoft.com/en-us/library/system.string.toupperinvariant.aspx
Convert to uppercase before switch like below,
grade = Char.ToUpper(grade);
Change
char grade = Convert.ToChar(Console.ReadLine());
To
char grade = Convert.ToChar(Console.ReadLine().ToUpper());
https://msdn.microsoft.com/en-us/library/system.string.toupper(v=vs.110).aspx
Write Switch on grade.ToUpper() like this and don't change change it's value, may be you will need it after
char grade = Convert.ToChar(Console.ReadLine());
switch (grade.ToUpper())
{
case 'A':
Console.WriteLine("Excellent Work!");
break;
case 'B':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
break;
}
You may fall from one case to another like this
public static void Main(string[] args)
{
Boolean validInputRead = false;
Char grade;
while(!validInputRead)
{
validInputRead = true;
Console.WriteLine("Please Input the Grade");
grade = Convert.ToChar(Console.Read());
switch (grade)
{
case 'A':
case 'a':
Console.WriteLine("Excellent Work!");
break;
case 'B':
case 'b':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
case 'c':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
case 'd':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
validInputRead = false;
break;
}
Console.ReadKey();
}
}
EDIT
Changed from Console.ReadLine() to Console.Read() as suggested
Added while(!validInputRead) as requested
string letterGrade;
int grade = 0;
// This will hold the final letter grade
Console.Write("Input the grade :");
switch (grade)
{
case 1:
// 90-100 is an A
letterGrade = "A";
Console.WriteLine("grade b/n 90-100");
break;
case 2:
// 80-89 is a B
letterGrade = "B";
Console.WriteLine("grade b/n 80-89");
break;
case 3:
// 70-79 is a C
letterGrade = "C";
Console.WriteLine("grade b/n 70-79");
break;
case 4:
// 60-69 is a D
letterGrade = "D";
Console.WriteLine(" grade b/n 60-69 ");
break;
default:
// point whic is less than 59
Console.WriteLine("Invalid grade");
break;
}
Anyway I don't know how I'm supposed to go about doing this... in my application I need to have the switch repeat itself if there's an invalid input. All the application does is exit as soon as I enter a different result. Here's my code:
string str = Console.ReadLine();
char option = char.Parse(str);
//Need to repeat this switch:
switch (option)
{
case 'N':
Console.WriteLine("Creating New App...");
break;
case 'L':
Console.WriteLine("Loading App...");
break;
case 'O':
Console.WriteLine("Loading Options...");
break;
case 'Q':
Console.WriteLine("Exiting Application...");
System.Environment.Exit(1);
break;
default:
Console.WriteLine("Invalid input.");
break;
}
Console.ReadLine();
Put the switch in a loop
bool invalidInput = true;
while (invalidInput)
{
string str = Console.ReadLine();
char option = char.Parse(str);
switch (option)
{
case 'N':
Console.WriteLine("Creating New App...");
invalidInput = false;
break;
case 'L':
Console.WriteLine("Loading App...");
invalidInput = false;
break;
case 'O':
Console.WriteLine("Loading Options...");
invalidInput = false;
break;
case 'Q':
Console.WriteLine("Exiting Application...");
System.Environment.Exit(1);
break;
default:
Console.WriteLine("Invalid input.");
break;
}
}
You could make use of a while statement.
bool shouldRun = true;
while(shouldRun)
{
switch (option)
{
case 'N':
Console.WriteLine("Creating New App...");
shouldRun = false;
break;
case 'L':
Console.WriteLine("Loading App...");
shouldRun = false;
break;
case 'O':
Console.WriteLine("Loading Options...");
shouldRun = false;
break;
case 'Q':
Console.WriteLine("Exiting Application...");
System.Environment.Exit(1);
break;
default:
Console.WriteLine("Invalid input.");
shouldRun = true;
break;
}
}
To repeat the switch you need to use one loop.I think you are looking for something like the following:
bool ExitFlag = true;
while (ExitFlag)
{
ExitFlag = false;
switch (option)
{
case 'N':
Console.WriteLine("Creating New App...");
break;
case 'L':
Console.WriteLine("Loading App...");
break;
case 'O':
Console.WriteLine("Loading Options...");
break;
case 'Q':
Console.WriteLine("Exiting Application...");
System.Environment.Exit(1);
break;
default:
Console.WriteLine("Invalid input.");
ExitFlag = true;
break;
}
}
Note How It Works:
Let the ExitFlag be a Boolean value that controls the while loop( stop iteration and exit the while when ExitFlag is false). and are initialized with true. in each time the control enters into the while the flag is set to false so that we can avoid setting it false in multiple cases. The flag will set to true only when the default case is executed(ie., the invalid output) hence the loop repeats in this condition only.
You can use the Goto: label option in C#.
Ref: https://msdn.microsoft.com/en-us/library/13940fs2.aspx
ReadAgain:
string str = Console.ReadLine();
char option = char.Parse(str);
//The switch itself:
switch (option)
{
case 'N':
Console.WriteLine("Creating New App...");
break;
case 'L':
Console.WriteLine("Loading App...");
break;
case 'O':
Console.WriteLine("Loading Options...");
break;
case 'Q':
Console.WriteLine("Exiting Application...");
System.Environment.Exit(1);
break;
default:
Console.WriteLine("Invalid input.");
goto ReadAgain;
break;
}
Console.ReadLine();
When I'm doing the code without the goto command it works, but when I add the :Start it get an 8 error.
Here is the relevant code:
:Start
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
break;
case "no":
Console.WriteLine("You choose no");
break;
default:
Console.WriteLine("{0},is not a word",what);
goto Start;
}
The correct syntax is Start:. But, instead of goto, you should set this up in a loop:
bool invalid = true;
while (invalid)
{
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
invalid = false;
break;
case "no":
Console.WriteLine("You choose no");
invalid = false;
break;
default:
Console.WriteLine("{0},is not a word",what);
}
}
Try "Start:" instead of ":Start"
like this:
Start:
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
break;
case "no":
Console.WriteLine("You choose no");
break;
default:
Console.WriteLine("{0},is not a word", what);
goto Start;
}
http://msdn.microsoft.com/en-us/library/aa664740(v=vs.71).aspx
The correct syntax for a label is Start:, not :Start
You can refactor your code to omit the goto statement instead (better):
bool continue = true;
while (continue) {
Console.Write("Do you want the yes or no?");
string what = Console.ReadLine();
switch (what)
{
case "yes":
Console.WriteLine("You choose yes");
continue = false;
break;
case "no":
Console.WriteLine("You choose no");
continue = false;
break;
default:
Console.WriteLine("{0}, is not a word",what);
break;
}
}
I was wondering if there was a way to do something like this in C#:
some loop here
{
Console.WriteLine("Please enter a or b");
switch (Console.ReadLine().ToLower())
{
case "a":
//some code here
break;
case "b":
//some code here
break;
default:
Console.WriteLine("Error, enter a or b");
repeat loop
}
}
It's probably a stupid question but something like that would be greatly beneficial to my assignment.
Why not. Run a while loop that exists only when a or b is entered.
bool condition = false;
Console.WriteLine("Please enter a or b");
string str = string.Empty;
while (!condition)
{
str = Console.ReadLine().ToLower();
switch (str)
{
case "a":
//some code here
condition = true;
break;
case "b":
//some code here
condition = true;
break;
default:
Console.WriteLine("Error, enter a or b");
break;
}
}
Console.WriteLine("You have entered {0} ", str);
Console.ReadLine();
What about something like this?
var acceptedValues = new List<string>()
{
"a",
"b",
};
Console.WriteLine("Please enter {0}", string.Join("or", acceptedValues));
var enteredValue = string.Empty;
do
{
enteredValue = Console.ReadLine().ToLower();
} while (!acceptedValues.Contains(enteredValue));