Local variables - switch case - c#

I am studying programming and I am very beginner (started 2 months ago).
I am doing a c# exercise for maths calculation. Our professor used a if ... else (embricated) loops to do the exercise. I wanted to use a switch case but I am struggling with the local variables.
I understand the issue: case 2 and 3 does not "know" the variables totalNumber and nbrSubAssy is as they come from case 1 and case 2, then they are detected as not assigned.
If I still want to use a switch case, what could I do to solve it?
using System;
namespace Denombrements
{
class Program
{
static long IntMultiplication(int startValue, int endValue)
{
long multiplication = 1;
for (int k = startValue; k <= endValue; k++)
multiplication *= k;
return multiplication;
}
static int UserSelection(String message)
{
int number = 0;
Console.Write(message);
try
{
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine();
Console.WriteLine("Wrong input, enter an integer");
}
return number;
}
static void Main(string[] args)
{
char choice = '1';
while (choice != '0')
{
Console.WriteLine("Permutation ...................... 1");
Console.WriteLine("Arrangement ...................... 2");
Console.WriteLine("Combination ...................... 3");
Console.WriteLine("Quit ............................. 0");
Console.Write("Choice : ");
choice = Console.ReadKey().KeyChar;
Console.WriteLine();
switch(choice)
{
case '0':
Environment.Exit(0);
break;
case '1':
int totalNumber = UserSelection("Total number of elements to be taken into account");
long permutation = IntMultiplication(1, totalNumber);
Console.WriteLine(totalNumber + "! = " + permutation);
break;
case '2':
int nbrSubAssy = UserSelection("Total number of elements in the subassy to be taken into account");
long arrangement = IntMultiplication(totalNumber - nbrSubAssy + 1, totalNumber);
Console.WriteLine("A(" + totalNumber + "/" + nbrSubAssy + ") = " + arrangement);
break;
case '3':
long combination = arrangement / IntMultiplication(1, nbrSubAssy);
Console.WriteLine("C(" + totalNumber + "/" + nbrSubAssy + ") = " + combination);
break;
default:
Console.WriteLine("Wrong input");
break;
}
}
Console.ReadLine();
}
}
}

Declare your variable before While loop and it will keep the value of it for all the life of LOOP and you could access the old values
char choice = '1';
int nbrSubAssy = 0;
int totalNumber = 0;
long arrangement = 0;
while (choice != '0')
{
// code ...
switch (choice)
{
case '0':
Environment.Exit(0);
break;
case '1':
totalNumber = UserSelection("Total number of elements to be taken into account");
long permutation = IntMultiplication(1, totalNumber);
Console.WriteLine(totalNumber + "! = " + permutation);
break;
case '2':
nbrSubAssy = UserSelection("Total number of elements in the subassy to be taken into account");
arrangement = IntMultiplication(totalNumber - nbrSubAssy + 1, totalNumber);
Console.WriteLine("A(" + totalNumber + "/" + nbrSubAssy + ") = " + arrangement);
break;
case '3':
long combination = arrangement / IntMultiplication(1, nbrSubAssy);
Console.WriteLine("C(" + totalNumber + "/" + nbrSubAssy + ") = " + combination);
break;
default:
Console.WriteLine("Wrong input");
break;
}
}
or in my opinion the better solution you could ask for the value in every case you need them

Related

for loop not executing/running correctly

Here's the code can anyone help?
using System;
namespace Mathhero
{
class MainClass
{
public static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
Random numgen = new Random();
int num1 = numgen.Next(1, 11);
int num2 = numgen.Next(1, 11);
Console.WriteLine("What is " + num1 + " * " + num2 + " equal to ???");
int Answer = Convert.ToInt32(Console.ReadLine());
if (Answer == num1 * num2)
{
int ran = numgen.Next(1, 4);
switch (ran)
{
case 1:
Console.WriteLine("Good work!!");
break;
case 2:
Console.WriteLine("Nice!!!");
break;
default:
Console.WriteLine("Excellent!!");
break;
}
Console.WriteLine();
}
else
{
int ran = numgen.Next(1, 4);
switch (ran)
{
case 1:
Console.WriteLine("Wrong!!");
break;
case 2:
Console.WriteLine("Try hard!!!");
break;
default:
Console.WriteLine("DO homework!!");
break;
}
Console.WriteLine();
}
i=i+ 1;
}
Console.WriteLine("Test Ended!!!");
}
}
}
The for loop is exiting after 6 questions while it should after 10.
You are increasing your index within the for loop and thus shortening it's run.
else
{
int ran = numgen.Next(1, 4);
switch (ran)
{
case 1:
Console.WriteLine("Wrong!!");
break;
case 2:
Console.WriteLine("Try hard!!!");
break;
default:
Console.WriteLine("DO homework!!");
break;
}
Console.WriteLine();
}
i=i+ 1; //// <------- HERE
}
Your for loop already takes care of incrementing the index by itself.
Your for loop "header" increments i in the normal way:
for (i = 0; i <= 10; i++)
However, within the loop you also increment i, for no apparent reason:
i=i+ 1;
So you're incrementing i twice for each iteration of the loop. That makes it reach its end point earlier.
To execute 10 times, you should have:
for (i = 0; i < 10; i++)
(note the use of < rather than <=) and remove the i = i + 1; statement entirely.
I'd also recommend the general principle of declaring each variable in as small a scope as you can - in this case, in the for loop:
for (int i = 0; i < 10; i++)
That's more idiomatic and "tidy" IMO than declaring it before the loop.
the loop will run for 11 times as you are initializing i=0 and i<=10 so should check this...
Second i don't understand why are you doing i+1 at the end because loop is already incrementing so you should check this also..

Control Cannot Fall Through From One Case Label To Another Even With Break

This is some part of the code.
I am getting the error "Control cannot fall through from one case label to another in case 3".
In spite of using the break statement, it is not getting detected. What is the right way to do it?
Update: Error is in case 3. Don't bother to waste your time on other cases.
switch (output)
{
case 1:
int num, reverse = 0;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
reverse = reverse * 10;
reverse = reverse + num % 10;
num = num / 10;
}
Console.WriteLine("Reverse of Number is : "+reverse);
Console.ReadLine();
break;
case 2:
int number, sum = 0, r,square;
Console.WriteLine("Enter a Number : ");
number = int.Parse(Console.ReadLine());
while (number != 0)
{
r = number % 10;
number = number / 10;
square = r * r;
sum = sum + square;
}
Console.WriteLine("Sum of square of Digits of the Number : "+sum);
Console.ReadLine();
break;
case 3:
Console.WriteLine("Enter 1 for AND 2 for OR and 3 for XOR Operation");
int answer = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your 2 inputs are?");
int inp1= Convert.ToInt32(Console.ReadLine());
int inp2= Convert.ToInt32(Console.ReadLine());
switch (answer)
{
case 1:
int input3 = inp1 * inp2;
System.Console.WriteLine("Output is" + input3);
Console.ReadLine();
break;
case 2:
int input4 = inp1 + inp2;
System.Console.WriteLine("Output is" + input4);
Console.ReadLine();
break;
case 3:
if (inp1 == inp2)
{
System.Console.WriteLine("OUTPUT IS 0");
Console.ReadLine();
}
else
{
System.Console.WriteLine("Output is 1");
Console.ReadLine();
}
break;
Your problem is that you only break out of the inner case and not the outer, so you're getting a fall through issue.
case 3 ...
case 3:
if (inp1 == inp2)
{
System.Console.WriteLine("OUTPUT IS 0");
Console.ReadLine();
}
else
{
System.Console.WriteLine("Output is 1");
Console.ReadLine();
}
break;
break; //break the outer case3
Add a goto case X in place of the break for where you want the fall though to occur.
... never mind. you need an expression block on the first case 3.
case 3
{
/// your other switch here
break;
}
By not using scoping blocks you overlooked the outer case statement. It needs break as well as the inner statement.

Timer with questions in c#

I have a cosole appliction
in this try to set timer that is when question display then timer should be start and when in 10 seconds answer not give then should start next question i want to do this
i am done with
I set 3 conditions first they should type number that how many question want to attemppt then select level then select operator .. so when all question typed i.e.
no of question : 2
level : 1
operator: +
then timer start of 10 seconds and when 10 seconds complete then question is display
where as i want first question display and timer then when question not answered with in 10 seconds then next should start
this is what i do
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int userans;
int computerans;
int numofquestions;
int numofquestionsleft;
int correctanswer = 0;
Console.WriteLine("\t\t OPERATOR OF QUIZ \t\t");
Console.WriteLine("\t\tOperator 1:Addition(+)\t\t");
Console.WriteLine("\t\tOperator 2:Subtarction(-)\t\t");
Console.WriteLine("\t\tLEVELS OF QUIZ\t\t");
Console.WriteLine("\t\tLevel 1 (1-9)\t\t");
Console.WriteLine("\t\tLevel 2 (10-99)\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.WriteLine("\t\tYour quiz start now\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.Write("How many questions do you want to attempt? ");
numofquestions = Convert.ToInt32(Console.ReadLine());
Console.Write("Which level that you want to play? ");
int level = Convert.ToInt32(Console.ReadLine());
Console.Write("which operator do you want to play?");
string opt = Console.ReadLine();
//for (int a = 10; a >= 0; a--)
//{
// Console.SetCursorPosition(0, 2);
// Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
// System.Threading.Thread.Sleep(1000);
//}
numofquestionsleft = numofquestions;
while (numofquestionsleft > 0)
{
if (level == 1)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(1, 10);
int num2 = rnd.Next(1, 10);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(1, 10);
num2 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(1, 10);
int num4 = rnd.Next(1, 10);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(1, 10);
num4 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
if (level == 2)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(10, 99);
int num2 = rnd.Next(10, 99);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(10, 99);
num2 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(10, 99);
int num4 = rnd.Next(10, 99);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(10, 99);
num4 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
//if(numofquestions>)
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(1000);
}
Console.ReadKey();
}
}
}
}
Your code is quite messy. You got everything in a single method. So creating additional method(s), which a timer needs, you cannot access any variable that is important to the timer. You need to start making your own classes. This gives you so much more control over the variables of your program. It is difficult with your code, to put you in the right direction. You need to change so much.
For fun, and some experience as well, I created what you was working on. A calculating game, or test, or w/e you wanna call it. I will share my code with you, in the hope you will learn some things out of it.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Program
{
static void Main(string[] args)
{
// Add different difficulty options
Dictionary<string, Difficulty> DifficultyOptions = new Dictionary<string, Difficulty>();
DifficultyOptions.Add("easy", new EasyDifficulty());
DifficultyOptions.Add("medium", new MediumDifficulty());
DifficultyOptions.Add("hard", new HardDifficulty());
// Add different game options
Dictionary<string, GameType> GameOptions = new Dictionary<string, GameType>();
GameOptions.Add("additive", new GameAdditive());
GameOptions.Add("subtractive", new GameSubtractive());
GameOptions.Add("randomize", new GameRandomize());
// Default game settings at start up
string GameDiff = "easy";
string GameMode = "additive";
Console.WriteLine("Welcome to Verkade's Calculating Game.");
Console.WriteLine("By default game difficulty has been set to " + GameDiff);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of DifficultOptions variable, and display them
foreach (KeyValuePair<string, Difficulty> kvp in DifficultyOptions)
{
Console.WriteLine("/difficulty " + kvp.Key);
}
Console.WriteLine("");
Console.WriteLine("By default game mode has been set to " + GameMode);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of game options and display them
foreach (KeyValuePair<string, GameType> GameTypes in GameOptions)
{
Console.WriteLine("/gamemode " + GameTypes.Key);
}
Console.WriteLine("");
Console.WriteLine("When you're done setting up, type in /start to start the game,");
Console.WriteLine("/stop to stop the game. /exit to stop entirely.");
//This will keep the instance of the game once started
Game CurrentGame = null;
//this will keep the program alive. By typing /exit, it will turn into false, and stops the program.
bool KeepProgramAlive = true;
//This is a loop that keeps on listening to your input
while (KeepProgramAlive)
{
// This will split up the users input, when a space is used.
// This way the first cut will contain /start, /stop, /gamemode, etc. It will be stored as 'UserInput[0]'
// In the second cut, which is 'UserInput[1]', things like 'easy', 'medium', 'hard', 'subtractive', etc will be stored
string[] UserInput = Console.ReadLine().Split(' ');
switch (UserInput[0])
{
case "/exit":
{
KeepProgramAlive = false;
break;
}
case "/start":
{
if (DifficultyOptions.ContainsKey(GameDiff) && GameOptions.ContainsKey(GameMode))
{
Console.WriteLine("Game has been set up. When you're ready, press Enter so you'll get your first question");
CurrentGame = new Game(DifficultyOptions[GameDiff], GameOptions[GameMode]);
}
break;
}
case "/stop":
{
if (CurrentGame != null)
{
CurrentGame.Stop();
CurrentGame = null;
Console.WriteLine("Game has been stopped. You can not change settings and start again if you like.");
}
break;
}
case "/gamemode":
{
// checking the length to see there are 2 values. /gamemode is 1 of them. 'subtractive' is another one.
if (UserInput.Length >= 2)
{
// very important, because i am using a dictionary, i can check whether the gamemode exists or not
if (GameOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed gamemode to " + UserInput[1]);
GameMode = UserInput[1];
}
else
{
Console.WriteLine("That gamemode does not exist");
}
}
break;
}
case "/difficulty":
{
if (UserInput.Length >= 2)
{
if (DifficultyOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed the difficulty to " + UserInput[1]);
GameDiff = UserInput[1];
}
else
{
Console.WriteLine("That difficulty does not exist");
}
}
break;
}
default:
{
// checking if the game has started, and if so, Handler in the game-class will check your input
if (CurrentGame != null)
{
int NumberGiven;
Int32.TryParse(UserInput[0], out NumberGiven);
CurrentGame.Handler(NumberGiven);
}
break;
}
}
}
}
}
}
Operators.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
abstract class GameType
{
public int Answer;
public Random Rnd = new Random();
public abstract string MakeSum(Difficulty Diff);
}
class GameAdditive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
}
class GameSubtractive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
class GameRandomize : GameType
{
public override string MakeSum(Difficulty Diff)
{
int mode = Rnd.Next(0, 2);
if (mode == 0)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
else
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
}
}
Game.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Game
{
Difficulty Game_Diff;
GameType Game_Type;
int TicksRemaining = 0;
int TotalAnswers = 0;
int CorrectAnswers = 0;
int WrongAnswers = 0;
Timer TimerCountdown;
public Game(Difficulty GDiff, GameType GType)
{
Game_Diff = GDiff;
Game_Type = GType;
TimerCountdown = new Timer(100);
TimerCountdown.Elapsed += TimerCD;
TimerCountdown.AutoReset = true;
}
public void Handler(int Answer)
{
if (TicksRemaining > 0)
{
if (Answer == Game_Type.Answer)
{
CorrectAnswers++;
Console.WriteLine("Good job. You got the correct answer.");
}
else
{
WrongAnswers++;
Console.WriteLine("Wrong answer. The answer was " + Game_Type.Answer + ".");
}
TotalAnswers++;
Console.WriteLine("Current score: " + CorrectAnswers + " correct answers out of " + TotalAnswers);
TicksRemaining = 0;
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
else
{
string SumText = Game_Type.MakeSum(Game_Diff);
Console.WriteLine("What is the solution to the sum " + SumText);
TicksRemaining = Game_Diff.Time;
TimerCountdown.Start();
}
}
public void TimerCD(Object source, ElapsedEventArgs e)
{
if(TicksRemaining > 0)
{
TicksRemaining--;
if ((TicksRemaining % 10) == 0)
{
Console.Write(Math.Floor((decimal)(TicksRemaining / 10)) + "...");
}
if (TicksRemaining == 0)
{
WrongAnswers++;
Console.WriteLine("\r\nTime is up. The answer was " + Game_Type.Answer);
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
}
}
public void Stop()
{
TimerCountdown.Stop();
}
}
}
Difficulty.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
// nice thing about abstract classes and child classes are that you can store a 'EasyDifficulty' object under variable-type 'Difficulty'
// this allows me to create a dictionary, with 'Difficulty' type as value, and yet put all the different child classes in there
// another thing you can do, and you can see it under 'Operators.cs' file, is that you can have a method, with the same name in every
// child class, and yet they perform different things.
abstract class Difficulty
{
public int MinNumber = 1;
public int MaxNumber = 1;
// Time in ticks. 1 tick = 100ms. Reason why I made it so is because maybe you want to give the player 7.5 seconds to do the sum
public int Time = 100;
}
class EasyDifficulty : Difficulty
{
public EasyDifficulty()
{
MinNumber = 1;
MaxNumber = 9;
Time = 100;
}
}
class MediumDifficulty : Difficulty
{
public MediumDifficulty()
{
MinNumber = 1;
MaxNumber = 99;
Time = 75;
}
}
class HardDifficulty : Difficulty
{
public HardDifficulty()
{
MinNumber = 1;
MaxNumber = 999;
Time = 50;
}
}
}
Your delay is only 1 second. Increase the delay to 10 seconds by:
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(10000);
}

Have a c# program close [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I need to have the program close if bool option = false. The "while (option == false)" statement is at the bottom of the code. Here is my code:
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)
{
double numA = 0;
double numB = 0;
double answer = 0;
string functionType;
string aLine;
string bLine;
string next;
bool option = true;
while (option == true)
{
Console.WriteLine("Enter a function type: ");
functionType = Console.ReadLine();
switch (functionType)
{
case "V":
Console.WriteLine(" + Addition" + '\n' + " - Subtraction" + '\n' + " * Multiplication" + '\n' + " / Division" + '\n' + " % Percent" + '\n' + " \\ Square Root" + '\n' + " ^ Exponent");
Console.WriteLine("Enter a function type: ");
functionType = Console.ReadLine();
break;
case "v":
Console.WriteLine(" + Addition" + '\n' + " - Subtraction" + '\n' + " * Multiplication" + '\n' + " / Division" + '\n' + " % Percent" + '\n' + " \\ Square Root" + '\n' + " ^ Exponent");
Console.WriteLine("Enter a function type: ");
functionType = Console.ReadLine();
break;
}
Console.WriteLine("Enter the first number: ");
aLine = Console.ReadLine();
numA = Double.Parse(aLine); Console.WriteLine("Enter the second number: ");
switch (functionType)
{
case "\\":
answer = Math.Sqrt(numA);
Console.WriteLine("The answer is: " + answer + '\n');
Console.WriteLine("Would you like to do more calculations? (Y/N): ");
next = Console.ReadLine();
switch (next)
{
case "Y":
option = true;
Console.WriteLine('\n');
break;
case "y":
option = true;
Console.WriteLine('\n');
break;
case "N":
option = false;
break;
case "n":
option = false;
break;
}
continue;
break;
case "%":
answer = numA * 100;
Console.WriteLine("The answer is: " + answer + '\n');
Console.WriteLine("Would you like to do more calculations? (Y/N): ");
next = Console.ReadLine();
switch (next)
{
case "Y":
option = true;
Console.WriteLine('\n');
break;
case "y":
option = true;
Console.WriteLine('\n');
break;
case "N":
option = false;
break;
case "n":
option = false;
break;
}
break;
continue;
}
Console.WriteLine("Enter the second number: ");
bLine = Console.ReadLine();
numB = Double.Parse(bLine);
switch (functionType)
{
case "+":
answer = numA + numB;
break;
case "-":
answer = numA - numB;
break;
case "x":
answer = numA * numB;
break;
case "*":
answer = numA * numB;
break;
case "X":
answer = numA * numB;
break;
case "/":
answer = numA / numB;
break;
case "^":
answer = Math.Pow(numA, numB);
break;
}
Console.WriteLine("The answer is: " + answer + '\n');
Console.WriteLine("Would you like to do more calculations? (Y/N): ");
next = Console.ReadLine();
switch (next)
{
case "Y":
option = true;
Console.WriteLine('\n');
break;
case "y":
option = true;
Console.WriteLine('\n');
break;
case "N":
option = false;
break;
case "n":
option = false;
break;
}
}
while (option == false)
{
}
}
}
}
Forgive me if this is an easy answer, but I have been learning c# for about 2 hours.
You don't need the while (option == false) loop at the end. What you do need to do, is check the value after each user input, and only proceed if the condition is not met. Ie, after each switch statement:
if (!option)
return;
This will exit from the outer while loop, and then the Main function will exit, thus ending your program.

"Member modifier 'static' must precede the member type and name" Error C#

I am building a game of BlackJack and the main class for it is having a problem. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class blackjack
{
static string[] playercards = new string[11];
static string hitstay = "";
static int total = 0, count = 1, dealertotal = 0;
static Random cardshuffler = new Random();
static Form1 f1 = new Form1();
Form1.ControlCollection
static void start()
{
dealertotal = cardshuffler.Next(15, 22);
playercards[0] = deal();
playercards[1] = deal();
bj();
}
private static void hit()
{
count += 1;
playercards[count] = deal();
f1.textBox2("you were dealed a(n) " + playercards[count] + ".your new total is " + total + ".");
if (total.Equals(21))
{
f1.textBox2("you got blackjack! the dealer's total was " + dealertotal + ".would you like to play again?");
playagain();
}
else if (total > 21)
{
f1.textBox2("you busted, therefore you lost. sorry. the dealer's total was " + dealertotal + ".would you like to play again? y/n");
playagain();
}
else if (total < 21)
{
do
{
f1.textBox2("would you like to hit or stay?");
hitstay = Console.ReadLine();
} while (!hitstay.Equals("hit") && !hitstay.Equals("stay"));
bj();
}
}
private static string deal()
{
string Card = "";
int cards = cardshuffler.Next(1, 14);
switch (cards)
{
case 1: Card = "Two"; total += 2;
break;
case 2: Card = "Three"; total += 3;
break;
case 3: Card = "Four"; total += 4;
break;
case 4: Card = "Five"; total += 5;
break;
case 5: Card = "Six"; total += 6;
break;
case 6: Card = "Seven"; total += 7;
break;
case 7: Card = "Eight"; total += 8;
break;
case 8: Card = "Nine"; total += 9;
break;
case 9: Card = "Ten"; total += 10;
break;
case 10: Card = "Jack"; total += 10;
break;
case 11: Card = "Queen"; total += 10;
break;
case 12: Card = "King"; total += 10;
break;
case 13: Card = "Ace"; total += 11;
break;
}
return Card;
}
static void bj()
{
if (hitstay.Equals("hit"))
{
hit();
}
else if (hitstay.Equals("stay"))
{
if (total > dealertotal && total <= 21)
{
Form1.textBox2.show("you won! the dealer busted with " + dealertotal + " as their total" + "your total was " + total);
playagain();
}
else if (total < dealertotal)
{
Form1.textBox2.show("sorry, you lost! the dealer's total was " + dealertotal );
playagain();
}
}
}
private static void playagain()
{
}
}
}
The error is in Line 21, Column 9.
The error is actually on line 17 - this identifier is hanging out to dry:
Form1.ControlCollection
Either you meant to declare a field or this code shouldn't be there. This code is causing a error later on since the parser is looking for a field name to go with the type you have put there and assumes that your static Main method is the identifier that goes with it.
static Form1 f1 = new Form1();
Form1.ControlCollection // What is this? You forgot to write something there?
static void start()
The compiler thinks that there is a declaration which starts with "Form1.ControlCollection" and continues with "static void start()".

Categories

Resources