C# do while Enter uppercase and lowercase letters in a string - c#

C # do while question.
What I want is the ability to terminate Q or q in upper case, lowercase letters in the source code.
I referenced MSDN but it did not work out, so I have a question here.
Thank you.
using System;
namespace Try
{
class Program
{
static void Main(string[] args)
{
string str1 = "Q";
string str2 = "q";
if (str1.Equals(str2, StringComparison.OrdinalIgnoreCase)) { }
string menu = "";
do
{
Console.WriteLine("Select Meun:(1)Triangle (2)Rectangle " +
"(Q)Quit",string.Equals
(str1, str2, StringComparison.CurrentCultureIgnoreCase));
menu = Console.ReadLine();
Console.WriteLine(menu + "is selected");
} while (menu != "Q");
}
}
}

Option 1
while (!string.Equals(menu, "Q", StringComparison.OrdinalIgnoreCase));
As the StringComparision suggests, this will ignore the case and treat q and Q as the same.
static void Main(string[] args)
{
string str1 = "Q";
string str2 = "q";
if (str1.Equals(str2, StringComparison.OrdinalIgnoreCase)) { }
string menu = "";
do
{
Console.WriteLine("Select Meun:(1)Triangle (2)Rectangle " +
"(Q)Quit",string.Equals
(str1, str2,
StringComparison.CurrentCultureIgnoreCase));
menu = Console.ReadLine();
Console.WriteLine(menu + "is selected");
} while (!string.Equals(menu, "Q", StringComparison.OrdinalIgnoreCase));
}
Option 2
while (menu.ToUpper() != "Q")
This will convert anything that is in the variable menu to uppercase. It's easier to read and does the job and I personally prefer this method.
static void Main(string[] args)
{
string str1 = "Q";
string str2 = "q";
if (str1.Equals(str2, StringComparison.OrdinalIgnoreCase)) { }
string menu = "";
do
{
Console.WriteLine("Select Meun:(1)Triangle (2)Rectangle " +
"(Q)Quit",string.Equals
(str1, str2,
StringComparison.CurrentCultureIgnoreCase));
menu = Console.ReadLine();
Console.WriteLine(menu + "is selected");
} while (menu.ToUpper() != "Q");
}
Addtional
There's also the example below that uses switch statements which are great and easier to read if you plan on having a lot of options in the future:
do
{
Console.WriteLine("Select Menu:(1)Triangle (2)Rectangle (Q)Quit");
menu = Console.ReadLine();
switch (menu.ToUpper())
{
case "1":
//DO SOME CODE
break;
case "2":
//DO SOME CODE
break;
case "Q":
return;
}
Console.WriteLine(menu + " is selected");
} while (true);
Or this method which doesn't use any StringComparison or ToUpper and would be use if you would want separate upper and lower case commands, or if you dont want to do any additional conversion/checking.
do
{
Console.WriteLine("Select Menu:(1)Triangle (2)Rectangle (Q)Quit");
menu = Console.ReadLine();
switch (menu)
{
case "1":
//DO THIS
break;
case "2":
//DO THAT
break;
case "q":
case "Q":
return;
}
Console.WriteLine(menu + " is selected");
} while (true);

Related

How do I repeat a question in a switch case

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");
}
}

How to rerun a code again in switch statement

Objective: Request users to input yes or no again when they type "idk" until they reply yes or no, how to rerun the ask and ans above?
Requirement: Not to use boolean.
static void Main(string[] args)
{
string ask = "Yes or No?";
Console.WriteLine(ask);
string ans = Console.ReadLine();
switch(ans)
{
case "yes":
yes();
break;
case "no":
no();
break;
case "idk":
//run "ask" again
}
}
Hmmm.. Normally you would use booleans and loop while the boolean is still true and set it to false when you get what you want.
But if you want to avoid booleans you can use an infinite loop and just return out of the function you are in when you are done:
class Program
{
static void Main(string[] args)
{
string ask = "Yes or No?";
for (;;)
{
Console.WriteLine(ask);
string ans = Console.ReadLine();
switch(ans.ToLower())
{
case "yes":
yes();
return;
case "no":
no();
return;
}
}
}
static void yes() => Console.WriteLine("Yes selected");
static void no() => Console.WriteLine("No selected");
}
I will be suggesting you use a do-while loop rather then goto statment
static void Main(string[] args)
{
NotFound:
string ask = "Yes or No?";
Console.WriteLine(ask);
string ans = Console.ReadLine();
switch (ans)
{
case "yes":
yes();
break;
case "no":
no();
break;
case "idk":
goto NotFound;
}
}
private static void no()
{
}
private static void yes()
{
}
switch(exp)
{
case "+":
Console.WriteLine("Enter Yor Number");
int PlusA = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Yor Number");
int PlusB = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
One more question I want to make a plus calculator, I want to let the user type more then 2 numbers, until they type the symbol ; how to do that?

How to correspond random numbers with a certain string?

I generate my random numbers with the Random num1 = new Random() method. I wanted to know if there was any way to have something like 10 different questions, each corresponding to a possible number. For example, when the random number 1 is generated, I want the question "What is the fastest animal?". I was able to do this quite easily, but every time I did the Console.ReadLine(); right afterward, the question before that changes on me. An example of what this would look like is this:
What is the fastest animal? > and then once I answered, it would show something like this:
An elephant's diet consists mostly of what? cheetah. How can I fix this?
Here is my code:
public class Program
{
public static void Main()
{
string[] incorrectAnswersJediSimple = new string[5];
Random JediS1 = new Random();
int randJediS1 = JediS1.Next(1, 4);
int totalScore = 0;
string JediQ11 = "JediQ11";
switch(randJediS1){
case 1:
JediQ11 = "Who is Luke Skywalker's father? ";
Console.Write(JediQ11);
string JediQ111 = Console.ReadLine();
if (JediQ111.Equals("Darth Vader", System.StringComparison.OrdinalIgnoreCase) || JediQ111.Equals("Vader", System.StringComparison.OrdinalIgnoreCase) || JediQ111.Equals("Anakin Skywalker", System.StringComparison.OrdinalIgnoreCase) || JediQ111.Equals("Anakin", System.StringComparison.OrdinalIgnoreCase)) {
totalScore++;
} else {
incorrectAnswersJediSimple[0] = "#1";
}
break;
case 2:
JediQ11 = "Who is Luke Skywalker's sister? ";
Console.Write(JediQ11);
string JediQ112 = Console.ReadLine();
if (JediQ112.Equals("Princess Leia", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Leia", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Leia Organa", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Leia Skywalker", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Princess Leia Organa", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Princess Leia Skywalker", System.StringComparison.OrdinalIgnoreCase)) {
totalScore++;
} else {
incorrectAnswersJediSimple[0] = "#1";
}
break;
case 3:
JediQ11 = "What is Darth Vaders real name? ";
Console.Write(JediQ11);
string JediQ113 = Console.ReadLine();
if (JediQ113.Equals("Anakin Skywalker", System.StringComparison.OrdinalIgnoreCase) || JediQ113.Equals("Anakin", System.StringComparison.OrdinalIgnoreCase) || JediQ113.Equals("Ani boi", System.StringComparison.OrdinalIgnoreCase) || JediQ113.Equals("ani", System.StringComparison.OrdinalIgnoreCase)) {
totalScore++;
} else {
incorrectAnswersJediSimple[0] = "#1";
}
break;
case 4:
JediQ11 = "What species is Admiral Ackbar? ";
Console.Write(JediQ11);
string JediQ114 = Console.ReadLine();
break;
case 5:
JediQ11 = "Who is Han Solo's Wookie sidekick? ";
Console.Write(JediQ11);
string JediQ115 = Console.ReadLine();
break;
case 6:
JediQ11 = "What species is Jar Jar Binks? ";
Console.Write(JediQ11);
string JediQ116 = Console.ReadLine();
break;
case 7:
JediQ11 = "On what planet does Luke first find Yoda in the original trilogy? ";
Console.WriteLine(JediQ11);
string JediQ117 = Console.ReadLine();
break;
case 8:
JediQ11 = "Who is Rey's grandfather? ";
Console.Write(JediQ11);
string JediQ118 = Console.ReadLine();
break;
case 9:
JediQ11 = "Who threw Mace Windu out of a window? ";
Console.Write(JediQ11);
string JediQ119 = Console.ReadLine();
break;
case 10:
JediQ11 = "What planet is Jedi Master Plo Koon from? ";
Console.Write(JediQ11);
string JediQ1110 = Console.ReadLine();
break;
default:
JediQ11 = "ERROR";
Console.WriteLine(JediQ11);
Console.Write("\nPress any key to continue...");
string ERROR11 = Console.ReadLine();
break;
}
}
}```

Case Switch with a loop

I am not understanding what is going on in my case statement to determine if I want to redo the users input. Should I make another loop outside of my while loop? I attempted such and my case statement becomes unreachable code. Maybe I am not understanding case-switch statements.
class Program
{
static void Main(string[] args)
{
string _a = "";
constructor con = new constructor();
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
bool control = true;
while (control)
{
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
control = false;
break;
case "M":
control = false;
metroid();
break;
case "A":
control = false;
Array();
break;
default: Console.WriteLine("No match");
break;
}
}
}
public class constructor
{
public string a = "This is a constructor!";
}
static public void metroid()
{
string b = "This is a method!";
Console.WriteLine(b);
}
static public void Array()
{
try
{
Console.WriteLine("This is a random array. Please enter the size.");
string sSize = Console.ReadLine();
int arraySize = Convert.ToInt32(sSize);
int[] size = new int[arraySize];
Random rd = new Random();
Console.WriteLine();
for (int i = 0; i < arraySize; i++)
{
size[i] = rd.Next(arraySize);
Console.WriteLine(size[i].ToString());
}
}
catch (System.FormatException)
{
Console.WriteLine("Not correct format, restarting array process.");
Array();
}
}
}
}
Here's what I came up with. You had too many ways of exiting your loop, so I removed all of the control = false lines except where the user typed "EXIT"
Also, in case "C" you return out of the method if they choose "Y", I changed that to continue so that the loop would continue.
Finally, I moved the 3 instruction statements into the loop, so when the user hit "Y" it would print those again.
static void Main(string[] args)
{
string _a = "";
constructor con = new constructor();
bool control = true;
while (control)
{
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
_a = Console.ReadLine(); //<==problem #1 you didnt set your var name
if (_a.ToUpper() == "Y")
{
continue; //<==problem #2 return exits the program, continue, just keeps going
}
control = false;
break;
case "M":
metroid();
break;
case "A":
Array();
break;
default:
Console.WriteLine("No match");
break;
}
}
}
I think you should considering goto in this case. Yes you need to put some extra effort, but it will help you overcoming the While loop.
A sample below:
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
// execute goto when your all line executes successfully
goto case "New";
case "New":
// some logic
}
See working sample here Goto-Switch
string NewInput= Console.ReadLine();
if (NewInput.ToUpper() == "Y")
{
//print some thing with console.writeline
//if after this you want to restart the loop then instead of return use
continue;
}
Try putting the Console.Writeline inside the while loop like this:
static void Main(string[] args)
{
bool control = true;
while (control)
{
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
string _a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine("press c");
Console.WriteLine("Would you like to test another scenario?");
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
control = false;
break;
case "M":
control = false;
metroid();
break;
case "A":
control = false;
Array();
break;
default: Console.WriteLine("No match");
break;
}
}
}
Additional reading about switch here and here.
Just add comment for the result, thanks. Hope this helped!
may be you want to change
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
as
_a = Console.ReadLine();
if (_a.ToUpper() == "Y")
{
_a = Console.ReadLine();
continue;
}

C# switch statement validation

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));

Categories