Method to output Messagebox messages - c#

Is there a better way to present the following method which prints out different messages depending on the parameters. Find it too wordy and lengthy and yet unable to simply it cos the messages differ at each line. Do advice if I could shorten it. Thank you.
private void message(int choice, string result)
{
if (choice == 1 && result == "Draw")
{
MessageBox.Show("It is a draw. Both chose Rock");
}
else if (choice == 2 && result == "Draw")
{
MessageBox.Show("It is a draw. Both chose Paper");
}
else if (choice == 3 && result == "Draw")
{
MessageBox.Show("It is a draw. Both chose Scissor");
}
else if (choice == 1 && result == "Win")
{
MessageBox.Show("Congratulations! Rock beats Scissor");
}
else if (choice == 2 && result == "Win")
{
MessageBox.Show("Congratulations! Paper beats Rock");
}
else if (choice == 3 && result == "Win")
{
MessageBox.Show("Congratulations! Scissor beats Paper");
}
else if (choice == 1 && result == "Lose")
{
MessageBox.Show("You lose. Paper beats rock");
}
else if (choice == 2 && result == "Lose")
{
MessageBox.Show("You lose. Scissor beats Paper");
}
else if (choice == 3 && result == "Lose")
{
MessageBox.Show("You lose. Rock beats Scissor");
}
}

Setup an enum to represent the possible choices:
public enum Choice
{
Rock = 1,
Paper = 2,
Scissor = 3
}
Then just use string.Format():
var selectedChoice = Enum.GetName(typeof(Choice), choice);
var beatsChoice = selectedChoice == Choice.Rock ? Choice.Scissor
: (selectedChoice == Choice.Paper ? Choice.Rock : Choice.Paper);
if (result == "Draw")
MessageBox.Show(string.Concat("It is a draw. Both chose ", selectedChoice);
else if (result == "Win")
MessageBox.Show(string.Concat("Congratulations! ", selectedChoice, " beats ", beatsChoice);
else if (result == "Lose")
MessageBox.Show(string.Concat("You lose. ", selectedChoice, " beats ", beatsChoice);

Dont know if this is a good idea but you can do like this:
private void message(int choice, string result)
{
if(result == "Draw")
{
switch (choice)
case 1: MessageBox.Show("It is a draw. Both chose Rock");
break;
case 2: MessageBox.Show("It is a draw. Both chose Paper");
break;
case 3: MessageBox.Show("It is a draw. Both chose Scissor");
break;
}
//similarly do for the rest.
}

Not sure I like your design, but given what you have this is (slightly) nicer to maintain ...
private void message(int choice, string result)
{
string self;
switch(choice)
{
case 1: self = "Rock"; break;
case 2: self = "Paper"; break;
case 3: self = "Scissor"; break;
}
switch(result)
{
case "Draw":
MessageBox.Show(String.Format("It is a draw. Both chose {0}", self));
break;
case "Win":
string beats;
switch(choice)
{
case 1: beats = "Scissor"; break;
case 2: beats = "Rock"; break;
case 3: beats = "Paper"; break;
}
MessageBox.Show(String.Format("Congratulations! {0} beats {1}", self, beats));
break;
case "Lose":
string loses;
switch(choice)
{
case 1: loses = "Paper"; break;
case 2: loses = "Scissor"; break;
case 3: loses = "Rock"; break;
}
MessageBox.Show(String.Format("You lose. {1} beats {0}", self, loses));
break;
break;
}
}
That said, this solution is still horribly ugly. A better way would to be passing around objects which encapsulate rock/paper/scissor states rather than "choice" ints. These would have methods to get what they beat. Printing would then be much simpler.

Another thing is that you could make the integer and string as Enum's this would allow you to print out the wording of the in very few lines of code.

Use enums to increase readability. I would also use two parameters since it's not clear who won:
public enum RockPaperScissors
{
Rock,
Paper,
Scissor
}
public enum GameResult
{
PlayerOneWin,
PlayerTwoWin,
Draw
}
Then the method can be shortened to:
private void message(GameResult result, RockPaperScissors choice1, RockPaperScissors choice2)
{
if (result == GameResult.Draw)
{
MessageBox.Show("It is a draw. Both chose " + choice1.ToString());
}
else
{
string message = string.Format("Congratulations, {0} beats {1}!"
, result == GameResult.PlayerOneWin ? choice1 : choice2
, result == GameResult.PlayerOneWin ? choice2 : choice1);
MessageBox.Show(message);
}
}

Related

How can I read a specific key in c# being anywhere in the program. c#

I'm a beginner programer that have started programming a week ago. As part of the learning to consolidate knowledge, I try to recreate my Toothbrush program. I want to dependent the program on two keys PowerButton and OptionButton.
Here's the code:
Console.WriteLine("Hello!");
int powerButtonCount = 0;
int optionButtonCount = 0;
if (Console.ReadKey().KeyChar == 'p')
{
powerButtonCount++;
while (powerButtonCount >= 1)
{
if (Console.ReadKey().KeyChar == 'o')
{
optionButtonCount++;
switch (optionButtonCount)
{
case 1:
Console.WriteLine("Sensitive");
while (powerButtonCount == 2 && optionButtonCount == 1)
{
Console.WriteLine("Brushing in Sensitive mode!");
}
break;
case 2:
Console.WriteLine("Gum Care");
while (powerButtonCount == 2 && optionButtonCount == 2)
{
Console.WriteLine("Brushing in Gum Care mode!");
}
break;
case 3:
Console.WriteLine("Intense");
while (powerButtonCount == 2 && optionButtonCount == 3)
{
Console.WriteLine("Brushing in Intense mode!");
}
break;
case 4:
Console.WriteLine("Daily Clean");
while (powerButtonCount == 2 && optionButtonCount == 4)
{
Console.WriteLine("Brushing in Daily Clean mode!");
}
break;
case 5:
Console.WriteLine("Whiten");
while (powerButtonCount == 2 && optionButtonCount == 5)
{
Console.WriteLine("Brushing in Whiten mode!");
}
break;
}
}
else if (powerButtonCount == 3)
{
powerButtonCount = 0;
Console.WriteLine("Good Bye!");
}
}
}
What I came across is problem that I can't read input from user in realtime. After my testing, seems like I'm able to jump between switches, but when I want to initialize "Brushing thing" C# doesn't read 'p'.

How do I access a variable from a switch statement? [duplicate]

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

How to get variable totalCredit to increment properly

In my program, I am supposed to have the user enter course selections, up to a max of 3. The problem I am running into is that in order for the switch to end at 3 courses, it has to update the value of totalCredit until it reaches 9 (which is a total of 3 courses worth 3 credits each). Basically, when you've already entered 3 courses and you try to enter a 4th, it should spit out case -3 from within the WritePrompt method, but it appears to not be changing the totalCredit variable at all.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleRegisterStudent
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
void run()
{
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
string yesOrNo = "";
System.Console.WriteLine("Teacher's Copy");
do
{
WritePrompt();
choice = Convert.ToInt32(Console.ReadLine());
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit))
{
case -1:
Console.WriteLine("Your entered selection {0} is not a recognized course.", choice);
break;
case -2:
Console.WriteLine("You have already registerd for this {0} course.", ChoiceToCourse(choice));
break;
case -3:
Console.WriteLine("You can not register for more than 9 credit hours.");
break;
case -4:
Console.WriteLine("Registration Confirmed for course {0}.", ChoiceToCourse(choice));
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
Console.Write("\nDo you want to try again? (Y|N)? : ");
yesOrNo = (Console.ReadLine()).ToUpper();
} while (yesOrNo == "Y");
Console.WriteLine("Thank you for registering with us");
}
void WritePrompt()
{
Console.WriteLine("Please select a course for which you want to register by typing the number inside []");
Console.WriteLine("[1]IT 145\n[2]IT 200\n[3]IT 201\n[4]IT 270\n[5]IT 315\n[6]IT 328\n[7]IT 330");
Console.Write("Enter your choice : ");
}
int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit)
{
if (choice < 1 || choice > 7)
return -1;
else if (choice == firstChoice && choice == secondChoice && choice == thirdChoice)
return -2;
else if (totalCredit > 9)
return -3;
return -4;
}
void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice)
{
if (secondChoice == 0)
Console.WriteLine("You are currently registered for {0}", ChoiceToCourse(firstChoice));
else if (thirdChoice == 0)
Console.WriteLine("You are currently registered for {0}, {1}", ChoiceToCourse(firstChoice), ChoiceToCourse(secondChoice));
else
Console.WriteLine("You are currently registered for {0}, {1}, {2}", ChoiceToCourse(firstChoice), ChoiceToCourse(secondChoice), ChoiceToCourse(thirdChoice));
}
string ChoiceToCourse(int choice)
{
string course = "";
switch (choice)
{
case 1:
course = "IT 145";
break;
case 2:
course = "IT 200";
break;
case 3:
course = "IT 201";
break;
case 4:
course = "IT 270";
break;
case 5:
course = "IT 315";
break;
case 6:
course = "IT 328";
break;
case 7:
course = "IT 330";
break;
default:
break;
}
return course;
}
}
}
No error messages, no build errors, it's the just program logic that isn't working.
When you've successfully entered 3 courses, totalCredit gets incremented by 3 for 3 times. Given its initial value of 0, the value of totalCredit while processing the 4th course entry would be 9
If you want to trigger the -3, you need to change:
else if (totalCredit > 9)
to:
else if (totalCredit >= 9)

Paper Scissors Rock using switches Visual Studio

I am relatively new to coding on c# and just wondering why I get a red underline on my "Else" line. can anyone help me??
class Program
{
static void Main()
{
string temp;
int number;
char computer = ' ', answer;
Random rand = new Random();
Console.WriteLine("Press p for paper, s for scissor or r for rock");
temp = Console.ReadLine();
answer = Convert.ToChar(temp);
number = rand.Next(3);
switch (number)
{
case 1:
computer = 'p';
Console.WriteLine("CPU chose paper");
break;
case 2:
computer = 's';
Console.WriteLine("CPU chose scissors");
break;
case 3:
computer = 'r';
Console.WriteLine("CPU chose rock");
break;
}
if (answer == computer)
{
Console.WriteLine("Draw");
}
else if (((answer == 'r')&&(computer == 's'))
||((answer == 's')&&(computer == 'p'))
||((answer == 'p')&&(computer == 'r')))
{
Console.WriteLine("You have won");
}
else (((answer == 's')&&(computer == 'r'))
||((answer == 'p')&&(computer == 's'))
||((answer == 'r')&&(computer == 'p')))
{
Console.WriteLine("You have lost");
}
Console.ReadLine();
}
}
You cant have conditions in else. I have converted your else with else if. below is corrected code
class Program
{
static void Main()
{
string temp;
int number;
char computer = ' ', answer;
Random rand = new Random();
Console.WriteLine("Press p for paper, s for scissor or r for rock");
temp = Console.ReadLine();
answer = Convert.ToChar(temp);
number = rand.Next(3);
switch (number)
{
case 1:
computer = 'p';
Console.WriteLine("CPU chose paper");
break;
case 2:
computer = 's';
Console.WriteLine("CPU chose scissors");
break;
case 3:
computer = 'r';
Console.WriteLine("CPU chose rock");
break;
}
if (answer == computer)
{
Console.WriteLine("Draw");
}
else if (((answer == 'r') && (computer == 's')) || ((answer == 's') && (computer == 'p')) || ((answer == 'p') && (computer == 'r')))
{
Console.WriteLine("You have won");
}
else if
(((answer == 's') && (computer == 'r')) || ((answer == 'p') && (computer == 's')) || ((answer == 'r') && (computer == 'p')))
{
Console.WriteLine("You have lost");
}
else
{
Console.WriteLine("In conclusive");
}
Console.ReadLine();
}
}
The else alone can't take a condition. To check a condition you need another if clause in the else branch:
if (condition) {
...
}
else if (other condition)
{
...
}

Using Random With Enumeration

Hi I am making a simple shotgun game where the user vs the computer and pick shoot, shield or reload But when I try to set the enumeration to random it gives me the error
Cannot implicitly convert type int to ShotgunGame.Program.ShotgunOption. An explicit conversion exists (are you missing a cast?),
I am not sure how to fix this.
Any Guidance would be appreciated
//Declare Variables
Console.Title = "Welcome To The Shotgune Game";
int CPUBullets = 3, userBullets = 3;
ShotgunOption UserOption;
int computerChoice, userScore = 0;
bool QUIT = false;
double gameCount = 0.0;
Random computer = new Random();
Console.Clear();
Console.WriteLine("SHOOT RELOAD SHIELD");
do
{
do
{
//Console.Write("Please enter choice, or enter QUIT to quit: ");
UserOption = GetOptionFromUser();
if (UserOption.ToUpper() == "QUIT")
{
break;
}
ShotgunOption CPUOption = computer.Next(1, 3); // 1 is Shot, 2 is Reload, 3 is Shield
switch (UserOption.ToUpper())
{
case "SHOOT":
if (computerChoice == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. It was a tie!", userChoice);
; userBullets --;CPUBullets --; ++gameCount;
}
else if (computerChoice == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You win!", userChoice);
++userScore; ++gameCount;
}
else if (computerChoice == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", userChoice);
++gameCount;
}
break;
case "RELAOD":
if (computerChoice == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. You lose!", userChoice);
++userScore; ++gameCount;
}
else if (computerChoice == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You Both Gain A bullet", userChoice);
userBullets++; CPUBullets++; ++gameCount;
}
else if (computerChoice == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", userChoice);
}
break;
case "SHIELD":
if (computerChoice == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. You lose!", userChoice);
++gameCount;
}
else if (computerChoice == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You win!", userChoice);
++userScore; ++gameCount;
}
else if (computerChoice == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", userChoice);
++gameCount;
}
break;
}
}
while (UserOption != ShotgunOption.Shield || CPUOption != 4);
} while (QUIT == false || gameCount == 3);
Shotgune game
As the error message suggests, you're trying to assign an int to a variable that is expecting an enum value. You can cast the int to an enum, though:
(EnumName)integerValue
So in this case:
ShotgunOption CPUOption = (ShotgunOption)computer.Next(1, 3);
Array values = Enum.GetValues(typeof(ShotgunOption));
Random computer = new Random();
ShotgunOption CPUOption = (ShotgunOption)values.GetValue(computer.Next(values.Length));
Try this...

Categories

Resources