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.
Related
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.
I have a WPF application which has random chances of random events occurring. I have a switch statement like so which switches a random number:
(property)
static Random RandomObject { get; set; } = new Random();
...
RandomObject = new Random();
switch (RandomObject.Next())
{
case 1 when RandomObject.Next(1, 3) == 2:
// a
case 1 when RandomObject.Next(1, 13) == 2:
// b
break;
}
For some reason, in debug mode, the whole switch is being skipped completely. Could someone tell me what I'm doing wrong or how I could possibly make it so it does work?
EDIT: Okay can someone tell me how to fix this instead because I remember coming up with something similar that does what I want to do and it did work but the problem is my hard drive crashed so I lost all of my data
Would this be possible?
switch(RandomObject)
{
case 1 when RandomObject.Next(1,3) == 2:
//do stuff
break;
}
I will run tests to try to show you what's going wrong. Let's take this code, which is similar to your own:
int acount = 0, bcount = 0;
var r = new Random();
for(var i = 0; i < 1_000_000_000; ++i) // 1 billion iterations
{
switch (r.Next())
{
case 1 when r.Next(1, 3) == 2:
++acount;
break;
case 1 when r.Next(1, 13) == 2:
++bcount;
break;
}
}
Console.WriteLine($"a case hit {acount} times");
Console.WriteLine($"b case hit {bcount} times");
The output is:
a case hit 0 times
b case hit 0 times
Now, let's try shrinking up your range on your switch statement:
// ...
switch (r.Next(1, 20))
{
// ...
Your results are now:
a case hit 26313397 times
b case hit 2191910 times
So what we are trying to tell you in the comments is Random.Next() returns a value in the range of [0, 2147483647], which is near unlikely to ever return the value of 1, which is what your switch cases require to continue. By changing your range with much more reasonable values, your chances increase dramatically and is more than likely what you want.
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.
My goal here is to ask the user to which of the three pre-determined ascii art picture they would like to print and how many times they would like to print it. My problem is that it print about 50 times more than whichever number was chosen. I tried converting the print variable, but that didn't work. I'm fairly new to C# so I apologize for any major, basic errors.
Console.WriteLine("Would you like to print picture 1, 2, or 3?");
int print = 0;
string choice = "";
while (choice != "end")
{
choice = Console.ReadLine();
switch (choice)
{
case "1":
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 10)
{
Console.WriteLine(cocaCola);
print -= 1;
}
break;
case "2":
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 10)
{
Console.WriteLine(beam);
print -= 1;
}
break;
case "3":
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 10)
{
Console.WriteLine(liberty);
print -= 1;
}
break;
default:
Console.WriteLine("You chose nothing");
break;
}
Console.WriteLine("Choose again, or type \"end\" to exit");
It's not printing 50 more times; it's printing exactly 48 more times.
You're reading a character and assigning its unicode value to an integer. For example, user types '1', the character 1. Its Unicode value is 49. You assign 49 to your int print, and there you are. A character is really a small or smallish integer, which is essentially an index into a table of characters somewhere.
In Unicode, as in ASCII, '0' is decimal 48, '1' is decimal 49, and so on in order up to '9'. That's where the 48 is coming from.
What you want to do is something more like this. First, you want to read the whole line, not just the first character; what if the user types "12"? Then you need parse the string "1" (or "12", which is two characters) to get the integer '1' or '12'.
And in fact, that's just what you did on this line:
print = Convert.ToInt32(Console.ReadLine());
So use that version every place that you've got print = Console.Read();
Second bug: You set print to some presumably small number, say the user types "4" so it's 4. Then you loop while it's greater than 10 -- but it's never greater than 10. You want to loop while it's greater than zero:
while (print > 0)
{
Console.WriteLine(cocaCola);
print -= 1;
}
You need to fix that in three places.
Update
Three places is more than you want to deal with. So here's another thing: You could simplify this code quite a bit by just setting a variable in the switch statement, and writing the loop only once (you could simplify it further in other ways, but let's take one step at a time):
Console.WriteLine("Would you like to print picture 1, 2, or 3?");
int print = 0;
string choice = "";
while (choice != "end")
{
choice = Console.ReadLine().Trim();
String thingToPrint = null;
switch (choice)
{
case "1":
thingToPrint = cocaCola;
break;
case "2":
thingToPrint = beam;
break;
case "3":
thingToPrint = liberty;
break;
}
if (thingToPrint != null)
{
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 0)
{
Console.WriteLine(thingToPrint);
print -= 1;
}
}
else
{
Console.WriteLine("You chose poorly. Try again.");
}
Console.WriteLine("Choose again, or type \"end\" to exit");
}
I haven't a living clue how to write this in c#. I know how to do it in Delphi.
This is how I would do it in Delphi:
Case Total of
80..100 : ShowMessage ('You got an A!');
60..79 : ShowMessage ('You got a B!');
50..59 : ShowMessage ('You got a C!');
40..49 : ShowMessage ('You got a D!');
0..39 : ShowMessage ('You got an E...');
end;
I have read tutorials for this, but I wouldn't know how to use/write it in the way I need it.
Here's my version in c#:
switch (Total) //'Total' is a bunch of Integers divided together to get a Percentage
{
case 80..100: //Where 80% to 100% would achieve an A
{
MessageBox.Show("You got an A!");
}
case 60..79: //Where 60% to 79% would achieve a B
{
MessageBox.Show("You got a B!");
}
Is this possible?
Thanks.
To express a range in a switch / case statement in C# you have to manually list out the cases
switch (Total) {
case 80:
case 81:
...
case 100:
MessageBox.Show("you got an A");
break;
...
}
For large ranges such as this though it may be better to just use a series of if statements
if (Total >= 80 && Total <= 100) {
MessageBox.Show("you got an A");
} else if (Total >= 70) {
MessageBox.Show("you got a B");
}
C# does not have a particularly flexible switch statement. This is intentional, options are limited to ensure that code generation is fast. C# has never been a language that hides execution cost. Runtime implementation is through a jump table, indexed by the switch() expression. Very fast, but not very flexible.
The alternative is an explicit if/else if chain. The exact same code that a VB.NET or Delphi compiler generates, but written by hand. Not terribly pretty, but effective enough:
if (Total < 0 || Total > 100) throw new ArgumentException("Not a valid grade");
if (Total >= 80) ShowMessage ('You got an A!');
else if (Total >= 60) ShowMessage ('You got a B!');
else if (Total >= 50) ShowMessage ('You got a C!');
else if (Total >= 40) ShowMessage ('You got a D!');
else ShowMessage ('You got an E...');
This now also shows the cost associated with the code, there can be up to 6 comparisons on the Total value. If speed is essential and the range is limited then consider switching to a lookup table, a Dictionary<>. Not necessary here, ShowMessage() is an expensive method.
If it is supposed to be a switch then it should be like this:
switch(Total)
{
case 100:
case 99:
//...
case 80:
MessageBox.Show("You got an A!");
break;
case 79:
// ...
}
If it is okay to use if-statements I would recommend to do it like this:
if (Total < 0)
{
}
else if (Total < 40)
MessageBox.Show("You got an E...")
else if (Total < 50)
MessageBox.Show("You got a D!");
else if (Total < 60)
// etc.
Hop you could use this answer.
AFAIK you can't do it natively in C# but if you want to do it with a switch, like you stated in your question, there is a workaround for that (for fixed ranges).
Considering your interval of 20 by 20:
int interval= (value-1) / 20;
switch (interval)
{
case 0: // 1-20
//Do stuffs
break;
case 1: // 21-40
//Do stuffs
break;
// and so on
}
A solution to solve your problem is to do it like this.
switch (Total)
{
case 1: case 2: case 3:
// Do Something
break;
case 4: case 5: case 6:
// Do Something
break;
default:
// Do Something
break;
}
Multiple Cases in Switch:
What about this?:
var s = "EEEEDCBBAAA";
var result = s[Total/10];
MessageBox.Show("you got a " + result);
Because Switch Statements Smells :)
Update
Didn't realize the a / an difference, but:
MessageBox.Show(string.Format("you got a{0} {1}",
result == "A" || result == "E" ? "n" : "",
result));
You could use a switch/case statement by creating a very long case statement or an extension method that turned a range of numbers into a constant. But it's probably easier to use an if/else block.
Personally, I like the readability of Enumerable.Range slightly over >= and <=. However, it is a slower operation because you're creating an enumerable of ints everytime you do a comparison. You'll probably on notice performance issues when you get in the tens of thousands of grads though.
if(Enumerable.Range(80,100).Contains(Total))
{
MessageBox.Show("You got an A!");
}
else if(Enumerable.Range(60, 79).Contains(Total))
{
MessageBox.Show("You got a B!");
}
else if(Enumerable.Range(50, 59).Contains(Total))
{
MessageBox.Show("You got a C!");
}
else if(Enumerable.Range(40, 49).Contains(Total))
{
MessageBox.Show("You got a D!");
}
else if(Enumerable.Range(0, 39).Contains(Total))
{
MessageBox.Show("You got an E...");
}
Use an action lookup (like a command pattern)
static void Main(string[] args)
{
var theGrade = 89;
var gradeLookup = new Dictionary<Func<int, bool>, Action>
{
{ x => x >= 90, () => ShowMessage("You got an A!") },
{ x => x >= 80 && x < 90, () => ShowMessage("You got an B!") },
};
gradeLookup.First(x => x.Key(theGrade)).Value();
Console.ReadKey();
}
static void ShowMessage(string msg)
{
Console.WriteLine(msg);
}
You can also simply divide by 10 to reduce the checks, but this would only work for some college scales:
static void Main(string[] args)
{
var theGrade = 80;
switch (theGrade / 10)
{
case 10:
case 9:
ShowMessage("You got an A");
break;
case 8:
ShowMessage("You got a B");
break;
case 7:
ShowMessage("You got a C");
break;
case 6:
ShowMessage("You got a D");
break;
default:
ShowMessage("You got a F");
break;
}
Console.ReadKey();
}
What about this code:
private string GetTotalCode(int total) {
if (Total >= 80 && Total <= 100)
return "A"
if ...
}
and then simplify switch:
switch (GetTotalCode(Total)) {
case "A":
MessageBox.Show("you got an A");
break;
...
}