errors using default for switch statement c# - c#

im trying to use default at the end of my switch statement and i keep getting errors! im getting frustrated please help
im very new to programming and its quite confusing lol
case "d":
Console.WriteLine("Please enter your option here:");
Console.WriteLine("First number");
double firstNum = Int32.Parse(Console.ReadLine());
Console.WriteLine("Second number:");
double secondNum = Int32.Parse(Console.ReadLine());
double sum = firstNum / secondNum;
Console.WriteLine("Result:" + sum);
Console.WriteLine("\n");
Console.ReadKey();
break;
}
default:
else if (number == 2)
{
Console.WriteLine("Exiting the code");
Console.WriteLine("Please press any key to exit");
Console.ReadLine();
break;
}
else
{
Console.WriteLine("Wrong selection");
Console.WriteLine("Please press any key to go to the main menu");
Console.ReadLine();
Active
Error CS1002 ; expected ConsoleApp50 69 Active
Error CS1513 } expected ConsoleApp50 69 Active
Error CS1513 } expected ConsoleApp50 98 Active

When the code is that weird, sometimes the error messages don't make sense :)
A few problems I see:
At the end of your case "d": block, you have a } where there was no previous {. Unless there is code in your case "d": block that you're not showing us, then you can just delete that }.
In your default: block, you're starting with an else if, where there was no if before that. You can only use else if after an if. Unless there's code you're not showing us, then you can change the else if to just if.
There's no } at the end, to close the else block.
You still need a break; at the end of the default: block.

Related

attempting to loop inside a switch

I have a menu with option.
Option 1: BMI caculator (option 1/case 1)
When entering the details in BMI calculator such as Height in Meters I am trying to get it to loop back and print an error message and ask again if the height that the user entered isn't a int (meters) for example if the user inputs a string say "M" it will not work and loops back to the initial question prompting for input IE: 2.1. I'm trying to use IF ELSE inside the switch/case. You can see in height section I can use goto case 1 to loop it but does not work for weight ( because that will go back to the beginning of case 1 and user would need to enter height again), Whatever the outcome of weight I need to keep the result of Height prior to weight so as to perform the final calculation BMI = . Sorry if this isn't clear, I'm really new and really stuck.
switch (optionsIn)
case 1:
{
Console.Clear();
Console.WriteLine("What is your height in meters");
double heightMax = 0.00;
string heightMeters = Console.ReadLine();
double.TryParse(heightMeters, out double heightM);
if (heightMax < heightM)
{
Console.Clear(); // nothing needs to run here , just clear to look better and move to collection of weight.
}
else
{
Console.Clear();
Console.WriteLine("Incorrect option try again");
Console.WriteLine("press enter to try again");
Console.ReadKey();
goto case 1; // better way to do it rather than goto case 1?
}
Console.WriteLine("Enter weight in Kgs"); // need to start here if incorrect input from user
double kgs = 00.00;
string weight = Console.ReadLine();
double.TryParse(weight, out double weightKgs);
if (kgs < weightKgs)
{
Console.Clear(); // nothing needs to run here , just clear console to look neat and move to calculating and printing BMI
}
else
{
Console.WriteLine("Incorrect option try again"); // cannot get to loop back to Enter weight
Console.WriteLine("press enter to return");
Console.ReadKey();
break;
}
double bmi = weightKgs / (heightM * heightM);
Console.WriteLine($"BmI is " + bmi);
Console.WriteLine("press any key to exit");
Console.ReadKey();
break;
}
I suggest method extraction:
public static double ReadDouble(string title, Func<double, bool> validation) {
// Keep Asking User until correct value is provided
while (true) {
// Show title if we have it
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (!double.TryParse(Console.ReadLine(), out double result))
// Not a double value at all; say, "bla-bla-bla"
Console.WriteLine("Syntax error. Please, try again.");
else if (validation != null && !validation(result))
// Not a valid double value, say, 123456.89 kg weight
Console.WriteLine("Not a valid value. Please, try again.");
else
return result;
}
}
then you can easily use it within switch \ case:
double heightM = ReadDouble("What is your height in meters", m => m > 0.3 && m < 3.0);
double weightKgs = ReadDouble("Enter weight in Kgs", m => m > 0.7 && m < 700.0);
double bmi = weightKgs / (heightM * heightM);
Console.WriteLine($"BmI is {bmi:F1}");
Instead of using goto - which is considered bad practice and is not all that much readable, try using a while or do/while loop instead.
Something like:
string input;
double heightMax = 0.0;
do {
input = Console.ReadLine();
double.TryParse(input, out double heightM);
Console.Clear();
} while (heightMax >= heightM);
Also, consider using functions for loading the data. Maybe you can think of some way of generalizing so that you can have only one function that you can reuse for all the stuff you need to load.

C# calculator user input issue

I am trying to create a C# calculator for a class, but when I try to use it it always returns blatantly wrong answers, like 1+3 = 100, or rounding down the decimal 2.33 to 50. It also crashes after the first input every time, which makes me think that its reading when i press enter for some reason, but I've looked and can't find documentation on any issue like that. Thanks in advance.
'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculator
{
class Program
{
static void Main(string[] args)
{
//set label for finished functions to return to
start:
System.Console.WriteLine("choose from one of the following calculator choices");
System.Console.WriteLine("1: whole number");
System.Console.WriteLine("2: addition");
System.Console.WriteLine("3: sine");
System.Console.WriteLine("4: cosine");
System.Console.WriteLine("5: absolue value");
System.Console.WriteLine("6: quit");
int optionSelect = Convert.ToInt32(Console.ReadLine());
switch (optionSelect)
{
case 1:
System.Console.WriteLine("whole number");
System.Console.WriteLine("give a decimal");
decimal temp = System.Console.Read();
System.Console.WriteLine(Convert.ToInt32(temp));
goto start;
case 2:
System.Console.WriteLine("addition");
System.Console.WriteLine("first int");
int add1 = Convert.ToInt32(System.Console.ReadKey());
System.Console.WriteLine("second int");
Console.ReadLine();
int add2 = Convert.ToInt32(System.Console.Read());
Console.ReadLine();
int answer = add1+add2;
System.Console.WriteLine("the answer is " + answer);
goto start;
case 3:
System.Console.WriteLine("sine");
System.Console.WriteLine("enter your angle in radians");
double numSin = Console.Read();
System.Console.WriteLine(Math.Sin(numSin));
goto start;
case 4:
System.Console.WriteLine("cosine");
System.Console.WriteLine("enter your angle in radians");
double numCos = Console.Read();
System.Console.WriteLine(Math.Cos(numCos));
goto start;
case 5:
System.Console.WriteLine("absolute value");
System.Console.WriteLine("enter a number");
double num = Convert.ToDouble(Console.Read());
System.Console.WriteLine(Math.Abs(num));
goto start;
case 6:
System.Console.WriteLine("shutting down...");
goto start;
default:
System.Console.WriteLine("invalid input");
goto start;
}
}
}
}
`
So there are multiple problems in your code.
Console.Read will return the corresponding ASCII code for the first character that you enter. Here is a link with the ASCII table: http://www.asciitable.com/
So if you put in the console 0 is not actually 0 but the corespondent value for 0 in the ASCII table. 0=48, 1=49, 2=50 ... 9 = 50.
If you put multiple characters only the first one will be processed by Console.Read.
To fix your problem you could use as you did in the begging :
string line = Console.ReadLine();
and after that, you can convert that line to whatever you need like decimal x = Convert.ToDecimal(line). or int x = Convert.ToInt32(line)
Also please try to change that goto logic into a while.

Setting random values from an Array into a List till condition is met. in C#

I want to set new random values from an Array into a List till one of two conditions is met. But it's only letting me add another 1 value without considering the condition. After I enter "y" the program letting me to get another value and then it asking me again if I want another card, when I enter "y" again , the code move on without letting me add another value.
The second problem is with the if(Hands.playerHand.Sum() > 22) I want the program to calculate the total value of the list and if it's more then 22 then execute the command.
Thank you!
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
while(secondHand)
{
//if user want another card, this programm will ganerate another card and store it inside playerHand
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
Console.ReadLine();
if(Hands.playerHand.Sum() > 22)
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
while (secondHandNo)
break;
So I changed the code a little. Now I can choose as many values as I want but I have a problem with the while (secondHandNo) and the while (Hands.playerHand.Sum() > 21) commands. When I enter "n" after taking another card the while (secondHandNo) which should continue the code wont executed. The while (Hands.playerHand.Sum() > 21) doesn't executed as well. It's just giving me more values no matter what my answer is. Note that when I enter "n" right away without taking another card, the command work just fine and it's taking me to the rest of the code.
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
while (secondHand)
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
Console.ReadLine();
}
while (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
while (secondHandNo)
break;
You have quite a few issues here:
You are not storing the result from the console. This can be solve easily:
userAnotherCard = Console.ReadLine();
Even if we stored it, in the while your condition checks a value that was previously assigned and is never changed. This the reason that you are in an endless loop. I would replace it simply with the condition itself:
while (userAnotherCard == "y")
It seems you are using while break instead of a simple if:
if (Hands.playerHand.Sum() > 21)
while (secondHandNo) break; is useless and can be removed from the code.
That should be enough. Final code can look like this:
string userAnotherCard = Console.ReadLine();
while (userAnotherCard == "y")
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
userAnotherCard = Console.ReadLine();
if (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
}
Ok I was able to fix this block of code. It seems to work now. I set the whole block into while loop and set each condition with an if statement and a break; if condition is met.
while (true)
{
Console.WriteLine("Would u like to take another card?");
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
if (secondHand)
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
}
if (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
if (secondHandNo)
break;
}

Console Keypress not working?

So I'm making a console-based text game to learn more C# but I'm now stuck and have resorted to SO.
This might be an obvious answer but I require another pair of eyes to help me. I've checked the other questions on here and they don't seem to aid me.
In my Main(), I have the following:
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
if (age < 18)
{
Console.WriteLine("I'm sorry, you'll now be transferred to a non-explicit version.");
Console.WriteLine("\n<Press any key to continue>");
Console.ReadKey();
Console.Write("\nPlease wait...");
for (int t = 5; t >= 0; t--)
{
Console.CursorLeft = 22;
Console.Write("{0:00}" + " seconds remaining", t);
Thread.Sleep(1000);
}
Console.WriteLine("");
Console.WriteLine("\nTo proceed, please press any key...");
Console.ReadLine();
NonExplicit();
}
Self explanatory. Once it hits the NonExplicit() method, the following is called:
char yes = Console.ReadKey().KeyChar;
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadKey().ToString();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
What seems to happen is that, when 'y' or 'Y' is pressed:
1) It requires enter to be hit to register the above.
2) It runs both the if & else WriteLines, which I assume is in conjunction with 1)?
How can I amend my code so that when 'y/Y' is pressed, it reads the correct criteria? Or how can I remove the need for Enter to be pressed to proceed?
Used your code below, I tested it and it works.
I moved the char yes = Console.ReadKey() to below the Console.WriteLine().
I changed the name = Console.ReadKey() to Console.ReadLine() because a name is more then 1 key.
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
char yes = Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadLine();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
Console.ReadKey(); // I put this here so the program wouldn't exit
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
In your code, after Console.WriteLine("\nTo proceed, please press any key..."); you have Console.ReadLine(); which expects you to enter a line in the console (not reading till you press enter) and then in your second method, you're trying to read the console again (but this time for a single key).
Wouldn't it help if you remove the first Console.ReadLine() ?
And then you are trying to get the yes/no answer before asking your question (and before doing another ReadKey.
string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
//any thing
}
char yes = Console.ReadKey(); // No need for .KeyChar
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
could be
int age = -1
Console.WriteLine("Before entering the unknown, could you please confirm your age? ");
while (age == -1)
{
if !(int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("Please enter a valid age");
}
}
name = Console.ReadKey().ToString();
should be
name = Console.ReadLine();
if (yes == 'y' || yes == 'Y')
could be
if (yes.ToUpper() == "Y")

Switch Case Causing Trouble In Going To A particular Function

FunWithScheduling fun = new FunWithScheduling();
Console.WriteLine("This Is Your Scheduler");
Console.WriteLine("What Do You Wish To Do");
Console.WriteLine("Enter 1 To Add, 2 To Edit, 3 To Search And 4 To Exit");
int Choice = Convert.ToInt32(Console.ReadLine());
switch (Choice)
{
case 1:
goto fun.Add();
break;
case 2:
goto fun.Edit();
break;
case 3:
goto fun.Search();
break;
case 4:
goto fun.Exit();
break;
Default:
Console.WriteLine("Enter a Valid Number");
return;
}
}
I got 4 functions that would help me do the following
Add
Edit
Search
Exit
I want to use switch case to go to the function. Is it possible?
It asked for an object reference and then a label.
Why don't you just call the method without the goto ? and for me it's not the proper way to use a goto, cfr MSDN Reference
This should be ok for me :
FunWithScheduling fun = new FunWithScheduling();
Console.WriteLine("This Is Your Scheduler");
Console.WriteLine("What Do You Wish To Do");
Console.WriteLine("Enter 1 To Add, 2 To Edit, 3 To Search And 4 To Exit");
int Choice = Convert.ToInt32(Console.ReadLine());
switch (Choice)
{
case 1:
fun.Add();
break;
case 2:
fun.Edit();
break;
case 3:
fun.Search();
break;
case 4:
fun.Exit();
break;
Default:
Console.WriteLine("Enter a Valid Number");
return;
}
}
Remove the goto. Those are only used if you are using labels. Simply call fun.Add() or fun.Edit()., etc.

Categories

Resources