This question already has answers here:
Switch variable to use externally
(5 answers)
Closed 8 months ago.
I have just started learning C# with one of brackey's tutorials, and I have tried to make a simple quiz. I have tried everything I could have thought to do (basically deleting instances of the variables I was having trouble with), and I can't find anything online that I can understand or implement into my current scenario.
using System;
namespace Learning_C_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Are you ready to solve some math equations?");
// I'm not sure what this indent is
if (Console.ReadLine() == "Yes")
{
Console.WriteLine("Definitely Generating Math Equations");
} else {
Console.WriteLine("Well thats too bad... You have too anyways");
}
Console.Write("Solve for x\n5x + 5 = 25\nx = ");
int ans01 = Convert.ToInt32(Console.ReadLine());
bool correct01 = false;
switch (ans01) {
case 4:
bool correct01 = true;
Console.WriteLine("Wow, you got it correct!\nThat's 1/3");
break;
default:
bool correct01 = false;
Console.WriteLine("Oops! You got that one incorrect...\n0/3");
break;
}
Console.Write("Solve\n75 + 2 * 12.5 = ");
int ans02 = Convert.ToInt32(Console.ReadLine());
bool correct02 = false;
switch (ans01){
case 100:
bool correct02 = true;
if(correct01 == true){
Console.WriteLine("Wow, you got it correct!\nThat's 2/3");
} else {
Console.WriteLine("Wow, you got it correct!\nThat's 1/3");
}
break;
default:
bool correct02 = false;
if (correct01 == true)
{
Console.WriteLine("Oops! You got that one incorrect...\n1/3");
}
else
{
Console.WriteLine("Oops! You got that one incorrect...\n0/3");
}
break;
}
Console.Write("Simplify\n5(4n + 3) = 23\nAnswer: ");
string ans03 = Convert.ToString(Console.ReadLine());
switch (ans03){
case "n = 1":
if(correct01 == true || correct02 == true){
Console.WriteLine("Wow, you got it correct!\nThat's 2/3");
} else if (correct01 == true && correct02 == true){
Console.WriteLine("Wow, you got it correct!\nThat's 3/3, congrats! You aced this test!");
}
break;
default:
if (correct01 == true || correct02 == true)
{
Console.WriteLine("Oops! You got that one incorrect...\n1/3");
}
else if(correct01 == true && correct02 == true){
Console.WriteLine("Oops! You got that one incorrect...\n2/3");
}
break;
}
// Wait before closing
Console.ReadKey();
}
}
}
My issue is I can't seem to reference these correct01 and 02 variables so that I can display the correct amount of points. I'm not sure if this is because they are defined in the switch statement but I can't seem to use them anywhere else. VS Code is also complaining that they are not used in the switch statement themselves.
Overall, I need a way to reference the correct01 and 02 variables from inside the switch statements.
Because you had decalred two variable with the same name.
Remove the bool that is in the switch statement
bool correct01 = false;
switch (ans01){
case 4:
correct01 = true;
Console.WriteLine("Wow, you got it correct!\nThat's 1/3");
break;
default:
correct01 = false;
Console.WriteLine("Oops! You got that one incorrect...\n0/3");
break;
}
Related
I am a complete newbie and i am stuck on a small problem
I want the user to only be able to have yes or no as an answer.
This is what I came up with
static public bool askBool(string question)
{
try
{
Console.Write(question);
return Console.ReadLine() == "y";
}
catch (Exception)
{
throw new FormatException("Only y or n Allowed");
}
}
The problem is entering any other letter then 'y' will result in false, how can I best solve this ?
Thank you in advance.
EDIT (from comment question)
try
{
Console.Write(question);
return int.Parse(Console.ReadLine());
}
catch (Exception)
{
throw new FormatException("Please Enter a Number");
}
I doubt if you want an exception to be thrown - there's nothing exceptional if the user puts OK instead of yes; I suggest to keep asking until "yes" or "no" are read:
public static AskBool(string question) {
while (true) {
// If we have a question to ask (the question is not empty one)...
if (!string.IsNotNullOrWhiteSpace(question))
Console.WriteLine(question); // ... ask it
// Trim: let be nice and trim out leading and trailing white spaces
string input = Console.ReadLine().Trim();
// Let's be nice and accept "yes", "YES", "Y" etc.
if (string.Equals(input, "y", StringComparison.OrdinalIgnoreCase) ||
string.Equals(input, "yes", StringComparison.OrdinalIgnoreCase))
return true;
else if (string.Equals(input, "n", StringComparison.OrdinalIgnoreCase) ||
string.Equals(input, "no", StringComparison.OrdinalIgnoreCase))
return false;
// In case of wrong user input, let's give a hint to the user
Console.WriteLine("Please, answer yes or no (y/n)");
}
}
Here the method will only return true or false if user has entered true or false.If user enters any word the loop will just continue to ask him for input until he enters y or n
you can give it a try by doing following changes
static public bool askBool(string question)
{
bool boolToReturn = false;
Console.Write(question);
while (true)
{
string ans = Console.ReadLine();
if (ans != null && ans == "y")
{
boolToReturn = true;
break;
}
else if ( ans != null && ans == "n")
{
boolToReturn = false;
break;
}
else
{
Console.Write("Only y or n Allowed");
}
}
return boolToReturn;
}`
Answer to second question:-
`
public static int askInt(string question)
{
Int intToReturn = false;
Console.Write(question);
while (true)
{
string ans = Console.ReadLine();
if (int.TryParse(and,out intToreturn))
break;
else
Console.Write("Only number Allowed");
}
return intToReturn;
}`
A bit more simplified version of Dmitry's answer with switch (what I normally do for this kind of scenarios):
static public bool askBool(string question)
{
while(true)
{
Console.Clear();
Console.Write(question);
var input = Console.ReadLine().Trim().ToLowerInvariant();
switch (input)
{
case "y":
case "yes": return true;
case "n":
case "no": return false;
}
}
}
Also I'd consider changing .ReadLine() to .ReadKey() because what we really need here is just 'y' or 'n'... One key is enough.
We use Exceptions mostly for scenarios when unexpected value will lead to some error. We don't throw an exception when we expect user to enter rubbish values and handle them.
You want to throw the exception, not catch it. Example:
static public bool askBool(string question)
{
Console.Write(question);
var input = Console.ReadLine();
if (input == "y")
{
return true;
}
else if(input == "n")
{
return false;
}
else//It's not y or n: throw the exception.
{
throw new FormatException("Only y or n Allowed");
}
}
Of course, you must then capture the 'FormatException' where you call this method.
Something like this?
if (Console.ReadLine() == "y")
{
return true;
}
else if (Console.ReadLine() == "n")
{
return false;
}
else {
throw new Exception("only y and n allowed...");
}
Here another idea:
public static bool ReadUserYesOrNo()
{
bool userSaysYes = true;
Console.Write("Y\b");
bool done = false;
while (!done)
{
ConsoleKeyInfo keyPressed = Console.ReadKey(true); // intercept: true so no characters are printed
switch (keyPressed.Key) {
case ConsoleKey.Y:
Console.Write("Y\b"); // print Y then move cursor back
userSaysYes = true;
break;
case ConsoleKey.N:
Console.Write("N\b"); // print N then move cursor
userSaysYes = false;
break;
case ConsoleKey.Enter:
done = true;
Console.WriteLine();
break;
}
}
return userSaysYes;
}
This will print the default value Y to the console. By pressing Y or N the user can toggle between the two values. The character in the console output will be overwritten. Pressing 'enter' selects the choice and the method returns the result.
I need to check a set of user Input from my console application before triggering my method and store data into my database.
The program compiles and rund without exceptions. But in case of one wrong Input it still runs through for the other three.
Although, what I really need is to make sure the 4 user's entries are correct before triggering the method and in case just one is wrong the whole program should stop and exit.
using System;
using System.Threading;
namespace BarcodeValidation
{
class Program
{
static void Main(string[] args)
{
ReadBarcode();
}
static void ReadBarcode()
{
var barcodes = GetInput();
foreach (var item in barcodes)
{
// something
CheckUserInput(item);
}
}
static string[] GetInput()
{
Console.WriteLine("Please enter 4 products ID, Barcodes, MPN or EAN code:");
string[] barcode = new string[4];
for (int i = 0; i < barcode.Length; i++)
{
barcode[i] = Console.ReadLine();
}
return barcode;
} // end of method here
static void CheckUserInput(string userInput)
{
int msec = 5000;
try
{
if (!(userInput == "F5121" || userInput == "F3111" || userInput == "F8331" || userInput == "F5321"))
{
Console.WriteLine("Enter a valid MPN codes for your products");
Thread.Sleep(msec);
Environment.Exit(0);
}
else
{
switch (userInput)
{
case "F5121":
Console.WriteLine("barcode 1 is =", userInput);
Thread.Sleep(msec);
break;
case "F3111":
Console.WriteLine("barcode 2 is =", userInput);
Thread.Sleep(msec);
break;
case "F8331":
Console.WriteLine("barcode 3 is =", userInput);
Thread.Sleep(msec);
break;
case "F5321":
Console.WriteLine("barcode 4 is =", userInput);
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Since you have a method that actually tests your user input use it's return value:
static bool CheckUserInput(string userInput) // true : valid | false : invalid
{
int msec = 5000;
try
{
if (!(userInput == "F5121" ||
userInput == "F3111" ||
userInput == "F8331" ||
userInput == "F5321"))
{
Console.WriteLine("Enter a valid MPN codes for your products");
return false;
}
else
{
switch (userInput)
{
case "F5121":
Console.WriteLine("barcode 1 is =", userInput);
Thread.Sleep(msec);
return true;
case "F3111":
Console.WriteLine("barcode 2 is =", userInput);
Thread.Sleep(msec);
return true;
case "F8331":
Console.WriteLine("barcode 3 is =", userInput);
Thread.Sleep(msec);
return true;
case "F5321":
Console.WriteLine("barcode 4 is =", userInput);
return true;
default:
return false;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
ReadBarcodes could look like this:
static void ReadBarcode()
{
var barcodes = GetInput();
bool errorOccured = false;
foreach (var item in barcodes)
{
// something
if(!CheckUserInput(item))
{
errorOccured = true; // keep track of that error
break; //Break for if 1 input is invalid
}
}
//Further execution....
if(errorOccured)
{
return; //Do not continue ...
}
//Do other things you want to do. Your input is valid at this point !
}
or shorter like Default quoted:
static void ReadBarcode()
{
if(!GetInput().All(CheckUserInput))
{
return;
}
//Your stuff goes here. Input is valid at this point
}
One option you could employ is create your own class that derives from System.Exception, and in cases where one of the inputs is found to be invalid, you could throw an instance of your exception class.
You could wrap your code in a try-catch block, and then put the remediation code within the catch block.
You need to break the checking code and the "output" code into different places. You need to check if all the values are valid values. and AFTER you have checked all the values, then do your console.writelines (Which is the part you dont want to happen). At the moment it checks one and executes the code if that one is valid, and then moves on to the next one. CheckUserInput should really ONLY check the users input, it should not do something else you want to restrict based on that methods result. You should have CheckUserInput and a ExecuteBarcodeStuff for example, and only if all CheckUserInputs return true, should you run the new (as yet unimplemented) ExecuteBarcodeStuff
Mixing this approach with other peoples answers that do Linq queries or such to ensure all the results were positive matches will get you the result you desire.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am a complete beginner at c# and i am making a tic tac toe game. I am having trouble understanding what is wrong with this code for my click property for each picture box i have 9 it breaks when i run it on visual studious:
private void pbxSquare0_Click(object sender, EventArgs e)
{
PictureBox pct = (PictureBox)sender;
int pic = Convert.ToInt32((pct.Name).Substring(10,1));
count++;
//switching the condition for each picture box
switch (pic)
{
case 1:
{
if (pict1 == 0) { pict1++; pbxSquare0.BackgroundImage = pictr; }
else if (pict1 == 2) { pbxSquare0.Enabled = false; } break;
}
case 2:
{
if (pict2 == 0) { pict2++; pbxSquare1.BackgroundImage = pictr; }
else if (pict2 == 2) { pbxSquare1.Enabled = false; } break;
}
case 3:
{
if (pict3 == 0) { pict3++; pbxSquare2.BackgroundImage = pictr; }
else if (pict3 == 2) { pbxSquare2.Enabled = false; } break;
}
case 4:
{
if (pict4 == 0) { pict4++; pbxSquare3.BackgroundImage = pictr; }
else if (pict4 == 2) { pbxSquare3.Enabled = false; } break;
}
case 5:
{
if (pict5 == 0) { pict5++; pbxSquare4.BackgroundImage = pictr; }
else if (pict5 == 2) { pbxSquare4.Enabled = false; } break;
}
case 6:
{
if (pict6 == 0) { pict6++; pbxSquare5.BackgroundImage = pictr; }
else if (pict6 == 2) { pbxSquare5.Enabled = false; } break;
}
case 7:
{
if (pict7 == 0) { pict7++; pbxSquare6.BackgroundImage = pictr; }
else if (pict7 == 2) { pbxSquare7.Enabled = false; } break;
}
case 8:
{
if (pict8 == 0) { pict8++; pbxSquare7.BackgroundImage = pictr; }
else if (pict8 == 2) { pbxSquare7.Enabled = false; } break;
}
case 9:
{
if (pict9 == 0) { pict9++; pbxSquare8.BackgroundImage = pictr; }
else if (pict9 == 2) { pbxSquare8.Enabled = false; } break;
}
default: break;
This isn't complete code but I do see a problem:
You are using the component name to figure out what box was clicked. (Bad idea--you should be using the Tag property!) However, the boxes are labeled 0 to 8 in that switch statement--but the box number extracted from the name is in the 1 to 9 range.
Whether this causes a crash I do not know--you don't have complete code to see what happens.
Also, look at lists or arrays to hold your boxes--there's no reason for a switch statement here.
How do I jump to another case statement in a switch-case condition with the value of current case statement?
Is it possible to implement this kind of things using switch case or is there another way to implement it?
Is it possible to achieve? If not, then is there another way to achieve it?
This code works:
switch (this.Name)
{
case "":
if (this.Owner == null)
{
goto DoBill;
}
break;
case "Bill":
DoBill:
break;
}
However, anyone who actually does it should be shot. Or talked to very severely, at the least. Why not just do the sensible thing?
switch (param.Component.Type)
{
case "Combo":
returnComboItemSelect = generateCB(param);
if(returnComboItemSelect=="Slider")
{
returnSomething = generateSl(param,returnComboItemSelect); //I mean no need to jump
}
break;
case "List":
returnSomething = generateL(param);
break;
case "Slider":
returnSomething
.....
Seriously, if you start jumping about between case statements then you shouldn't be using them. I'm not too keen on the code above either (duplication, but sometimes...)
You could but a while loop around the switch statement and break out of the loop when you are done.
var keepLooping = true;
var switchCaseSwitch = param.Component.Type;
while(keepLooping)
{
switch (switchCaseSwitch)
{
case "Combo":
returnComboItemSelect = generateCB(param);
if (returnComboItemSelect == "Slider")
{
switchCaseSwitch = "Slider";
}
else
{
keepLooping = false;
}
break;
case "List":
returnSomething = generateL(param);
keepLooping = false;
break;
case "Slider":
returnSomething = generateSl(param,1);
keepLooping = false;
break;
case "RadioButtons":
returnSomething = generateRB(param);
keepLooping = false;
break;
case "CheckBox":
returnSomething = generateCHB(param,flag);
keepLooping = false;
break;
default:
throw new Exception("Unknown component type");
}
}
Or you could ditch the case statement and do something like that:
//Setup
var selector = new Dictionary<string, Func<Param, string, string>>();
selector.Add("Combo", (p, flag) =>
{
var returnComboItemSelect = generateCB(p);
if (returnComboItemSelect == "Slider")
{
return selector["Slider"](p, returnComboItemSelect);
}
return returnComboItemSelect;
});
selector.Add("List", (p, flag) => { return generateL(p); });
selector.Add("Slider", (p, flag) => { return generateSL(p, flag); });
selector.Add("RadioButtons", (p, flag) => { return generateRB(p); });
selector.Add("CheckBox", (p, flag) => { return generateCHB(p, flag); });
//use
var result = selector[param.Component.Type](param, flag);
I think you would be FAR better off rethinking your architecture.
People dont tend to use GOTO in C# these days unless they are trying to break nested loops.
for example
foreach(var item in items){
foreach(var name in item.people){
if(name == WhatIAmSearchingFor)
goto found;
}
}
found:
//Your Code
MSDN Reference on GOTO
Something as simple as returning a Func, and a property bag of params is a clearer way to do this. Or like I have in the example below just do your first param and then an enum or flag of some sort. Instead of passing an empty one just make it 0
Here is a S.O. answer on how to do this Can a C# method return a method?
So in your example you might do this
public Func<ParamType,int> YourMethodName{
YourSwitch{
case(1)
return YourClassName.YourMethod;
break;
case(2)
return YourClassName.YourMethod2;
break
case(3)
return YourClassName.YourMethod3;
break
}
}
You can use a goto case.
A common use case is when you want one case to run to the next case.
switch ( arg )
{
case "-file":
if ( (i + 1) < args.Length && !args[i + 1].StartsWith("-") )
inputBox.Text = args[++i];
break;
case "-language":
_loadSelectedLanguagesAsALanguageSet = true;
goto case "-select";
case "-select":
if ( (i + 1) < args.Length && !args[i + 1].StartsWith("-") )
_loadSelectedLanguageFileOnStartup = args[++i];
break;
}
This is code for inserting value to database but Radio button list value is not converted and inserting failed.
using (SathsurEntities se = new SathsurEntities())
{
tbl_Events user = new tbl_Events();
user.Event_name = txtEventName.Text;
user.Event_date = Convert.ToDateTime(txtEventDate.Text);
user.Image_url = lblimg.Text;
user.Is_free_entry = Convert.ToBoolean(rblEntry.SelectedValue);
user.Booking_url = txtBooking.Text;
se.AddTotbl_Events(user);
se.SaveChanges();
Response.Write("Event Added Successfuly!");
}
a simple answer,
private bool value=true;
if (rblEntry.SelectedValue == "1")
{
value = true;
}
else if (rblEntry.SelectedValue == "2")
{
value = false;
}
user.Is_free_entry = value;
user.Is_free_entry = rblEntry.SelectedValue == "1";
OR
user.Is_free_entry = rblEntry.SelectedValue != "2";
If you can guarantee that all you ever get is either 1 or 2, then these are identical. If you want to try and catch other values, then the first (== "1") emphasizes that you ONLY get true when the value is 1 and you get false for all other values. The second (== "2") says you ONLY get false if the value is 2 and you get true for all other values. Thus, you can set a default on what to do if you get odd values. If you want to detect odd values and throw an exception or do other error handling, then you'll want to go with Vikas Rana's suggestion, but with an additional else
If you are only want to have two value , should have 'true' and 'false', it's enough .
if you have more value or more type ,you can use the type of byte or int ....
the you should use the if ... else ... or switch ... case ...
<asp:RadioButtonList ID="rblList" runat="server">
<asp:ListItem Text="True" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:RadioButtonList>
var a = Convert.ToBoolean(rblList.SelectedValue);
or
var a = Convert.ToInt16(rblList.SelectedValue);
var retValue = string.Empty;
switch (a)
{
case 0:
//"you want have"
break;
case 1:
//"you want have"
break;
case 2:
//"you want have"
break;
default:
//"you want have"
break;
}
or
if (a == 0)
{
//"you want have"
}
else if (a == 1)
{
//"you want have"
}
else if (a == 2)
{
//"you want have"
}
else
{
//"you want have"
}
this is where you might use an extension method along the lines of this:
public static class BooleanExtensions
{
public static bool ToBool(this string value)
{
bool result = false;
switch (value.ToLower().Trim())
{
case "y":
case "yes":
case "1":
result = true;
break;
case "n":
case "no":
case "0":
result = false;
break;
}
return result;
}
}
usage:
var value="0";
Console.Write(value.ToBool());
Should output false.
to use in your project, include that class above. You would use this in your code example like so
using (SathsurEntities se = new SathsurEntities())
{
tbl_Events user = new tbl_Events();
user.Event_name = txtEventName.Text;
user.Event_date = Convert.ToDateTime(txtEventDate.Text);
user.Image_url = lblimg.Text;
user.Is_free_entry = rblEntry.SelectedValue.ToBoolean();
user.Booking_url = txtBooking.Text;
se.AddTotbl_Events(user);
se.SaveChanges();
Response.Write("Event Added Successfuly!");
}