First C# program with two Classes. Confused - c#

pretty new to programming and I'm a bit stuck. This is the first program I've written with two classes (in two seperate class files). I'll include all the code below. It's a program to play a dice game called Craps. My task is too create a method in the CrapsGame class that allows me to play the game over and over again until I decide to stop. But I'm having a little trouble working out how to correctly call the manyPlay() method. I'm not really sure what I'm doing. The program will play the game once by calling myCraps.play() but then won't go any further. If anyone else notices anything wrong with the code or anything that's bad practice then please point it out as I am very keen to learn. Thanks to anyone that takes the time to answer.
using System;
namespace Task4_7
{
public class CrapsGame
{
string replay;
private Craps myCraps;
private CrapsGame newGame;
public static void Main()
{
CrapsGame newGame = new CrapsGame();
Craps myCraps = new Craps ();
myCraps.play ();
newGame.manyPlay ();
}
public void manyPlay() {
string input; // declare local variable
do {
myCraps.play();
replay:
Console.Write("Would you like to play again? y/n");
input = Console.ReadLine();
if (input == "y") {
replay = input;
}
else if (input == "n") {
replay = "n";
}
else {
Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
goto replay;
}
}
while(replay != "n");
}
}
}
using System;
namespace Task4_7
{
public class Craps
{
private Random randy; // define randy as a Random class
public Craps() {
this.randy = new Random ();
}
public int oneThrow() {
return randy.Next(6) + 1; // pick a number from 1 to 6 and return this
}
public int throw2Dice() {
int a, b, c;
a = oneThrow ();
b = oneThrow ();
c = a + b;
Console.WriteLine ("You threw a " + a + " and a " + b + " making " + c);
return c;
}
public void play() {
int result = throw2Dice ();
switch (result) {
case 2:
Console.WriteLine ("You lose! End of game!");
break;
case 3:
Console.WriteLine ("You lose! End of game!");
break;
case 12:
Console.WriteLine ("You lose! End of game!");
break;
case 7:
Console.WriteLine ("You win! End of game!");
break;
case 11:
Console.WriteLine ("You win! End of game!");
break;
case 4:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 5:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 6:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 8:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 9:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
default:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
}
}
public void throwPoint(int result) {
Throw:
int a = throw2Dice();
if (a == result) {
Console.WriteLine ("You rolled the same score! You win!");
} else if (a == 7) {
Console.WriteLine ("You rolled a 7! You loose!");
} else {
Console.WriteLine ("You rolled a " + a + ". Rolling again!");
goto Throw;
}
}
}
}

This is your problem:
Craps myCraps = new Craps();
You are hiding variable of class CrapsGame with a local variable of Main method. Simply change it to
myCraps = new Craps();
and it should work.
EDIT
and change myCraps declaration to static, of course.
EDIT2
Scope of variables: C# variable scoping not consistent?

My first suggestion is put your Main method in a seperate file.For example you can use three files: Program.cs, CrapsGame.cs, Craps.cs. To do this just add a new class file,and move your main method to new Class file. Second, never use goto.Instead use while loop like this,
public void throwPoint(int result) {
while(true)
{
int a = throw2Dice();
if (a == result) {
Console.WriteLine ("You rolled the same score! You win!");
break;
} else if (a == 7) {
Console.WriteLine ("You rolled a 7! You loose!");
break;
} else {
Console.WriteLine ("You rolled a " + a + ". Rolling again!");
}
}
}
Many play method:
public void manyPlay() {
string input; // declare local variable
myCraps.play();
while(true) {
Console.Write("Would you like to play again? y/n");
input = Console.ReadLine();
if (input == "y") {
myCraps.play();
}
else if (input == "n") {
break;
}
else {
Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
}
}
}

The problem looks like you where creating a game for use by the game iterator, but it needs to create a game for each iteration. So I delete some code: all the class variables have to go, variables should be as local as possible.
using System;
namespace Task4_7
{
public class CrapsGame
{
public static void Main()
{
new Craps ().play ();
new CrapsGame().manyPlay ();
}
public void manyPlay() {
string replay;
string input; // declare local variable
do {
new Craps().play();
replay:
Console.Write("Would you like to play again? y/n");
input = Console.ReadLine();
if (input == "y") {
replay = input;
}
else if (input == "n") {
replay = "n";
}
else {
Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
goto replay;
}
}
while(replay != "n");
}
}
}
Now fix that loop: no gotos. You need a loop in a loop, as you have but don't build your own loops.
Then if Craps.play() returned a score. You could add a class variable to accumulate the score.

Change replay to boolean and make set it to true if input is y and false if input is n.
Then change your main method.
public static void Main()
{
CrapsGame newGame = new CrapsGame();
Craps myCraps = new Craps ();
while (replay == true) {
myCraps.play ();
newGame.manyPlay ();
}
}

Related

Stack overflow exception with instances of classes

In my Main Menu class, I have a switch statement that calls the DisplaySellMenu method in the sell menu class(instance of the sell menu class was created in main menu class) when the user types the number to go to the sell menu. I then created a new instance of the Main menu class in the Sell Menu class, below you can see the switch statement I made so that when the user selects to exit to the Main Menu it calls the DisplayMainMenu method in the MainMenu class so the user can go back to the MainMenu. This is causing a stack overflow exception between the instances of the classes. How do I stop this from happening while still allowing the user to exit back to the main menu?
Main menu class:
class MainMenu
{
public BuyMenu buyMenu = new BuyMenu();
public SellMenu sellMenu = new SellMenu();
public ShipGarage shipGarage = new ShipGarage();
int Exit = 0;
public void DisplayMenu()
{
Console.WriteLine("Whatcha tryin to do yo?");
Console.WriteLine("Type 1 to buy");
Console.WriteLine("Type 2 to sell");
Console.WriteLine("Type 3 for SpaceShip Upgrade ");
Console.WriteLine("Type 4 to quit game");
int userSelection = int.Parse(Console.ReadLine());
do
{
switch (userSelection)
{
case 1:
buyMenu.DisplayInventory(buyMenu);
DisplayMenu();
break;
case 2:
sellMenu.SoldItems();
DisplayMenu();
break;
case 3:
shipGarage.DisplayGarage(shipGarage);
DisplayMenu();
break;
case 4:
Exit += 1;
break;
default:
Console.WriteLine("Invalid Input");
break;
}
} while (Exit == 1);
}
}
Sell menu class:
class SellMenu
{
static Random rnd = new Random();
MoneyMath Money = new MoneyMath();
MainMenu MainMenu = new MainMenu();
int goldPrice = rnd.Next(100, 1001);
int silverPrice = rnd.Next(100, 1001);
int titaniumPrice = rnd.Next(100, 1001);
int Exit = 0;
public string DisplayInventory()
{
Console.WriteLine("What would you like to sell?");
Console.WriteLine("Type 1 for Gold");
Console.WriteLine("Type 2 for Silver");
Console.WriteLine("Type 3 for Titanium");
Console.WriteLine("Type 4 for Main Menu");
string itemList = "Gold" + " " + "$" + (goldPrice) + "\n" +
"Silver" + " " + "$" + (silverPrice) + "\n" +
"Titanium" + " " + "$" + (titaniumPrice);
Console.WriteLine(itemList);
return itemList;
}
public void SoldItems()
{
do
{
DisplayInventory();
int userSelection = int.Parse(Console.ReadLine());
switch (userSelection)
{
case 1:
Money.MoneyAddition(goldPrice, 1);
Console.WriteLine(Money.userMoney);
break;
case 2:
Money.MoneyAddition(silverPrice, 1);
Console.WriteLine(Money.userMoney);
break;
case 3:
Money.MoneyAddition(titaniumPrice, 1);
Console.WriteLine(Money.userMoney);
break;
case 4:
Exit += 1;
MainMenu.DisplayMenu();
break;
default:
Console.WriteLine("Invalid Input");
break;
}
} while (Exit == 1);
}
}
It seems to me that your SoldItems() case 4 should simply be this:
case 4:
return;
You're already calling SoldItems() from DisplayMenu() in MainMenu, so all you need to do is return to the DisplayMenu() switch statement and continue its loop.
Having an Exit variable is unnecessary here because return will leave the entire method body, terminating the while loop. The same applies to DisplayMenu()'s Exit variable, too.
Complete code for SoldItems():
public void SoldItems()
{
do
{
DisplayInventory();
int userSelection = int.Parse(Console.ReadLine());
switch (userSelection)
{
case 1:
Money.MoneyAddition(goldPrice, 1);
Console.WriteLine(Money.userMoney);
break;
case 2:
Money.MoneyAddition(silverPrice, 1);
Console.WriteLine(Money.userMoney);
break;
case 3:
Money.MoneyAddition(titaniumPrice, 1);
Console.WriteLine(Money.userMoney);
break;
case 4:
return;
default:
Console.WriteLine("Invalid Input");
break;
}
}
while (true);
}
Explanation of StackoverflowException:
This exception is caused when the stack gets full. Imagine you have three methods:
public void A() { B(); }
public void B() { C(); }
public void C() { }
When A calls B, an extra layer is pushed onto the stack. The same happens when B calls C. When C returns to B, that layer is pushed off the stack, and then the same then B returns to A.
The .NET stack has a finite size, so you can't infinitely call methods. This is typically big enough for any code you write, except recursive functions can be a little dangerous. Imagine this code:
public void A() { A(); }
It calls itself recursively forever. This code is doomed to experience a Stackoverflow exception. When you write code like this, you need to place a limitation on it to ensure that it only goes so deep. Example:
public void A(int maxDepth = 0) { if (maxDepth < 5) { A(++maxDepth); } }
You can read more about the stack and this exception here.
Obligatory Google Easter egg

goto - not within scope (C#)

I am very new to code. Can anyone in a simple way explain why I cant use the goto statement like this, to make the code start over again? Or, how this could have been done in the correct way? And also, why I get an error message on the use of "static".
**
"No such label "Start" within the scope of the goto statmenet"
"The modifier static is not valid for this item"
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Start:
Random numberGenerator = new Random();
int num1 = numberGenerator.Next(1,11);
int num2 = numberGenerator.Next(1, 4);
Console.WriteLine("What is " + num1 + " times " + num2 + "?");
int svar = Convert.ToInt32(Console.ReadLine());
if (svar == num1 * num2)
{
Console.WriteLine("well done!");
}
else
{
int responseIndex = numberGenerator.Next(1, 4);
switch (responseIndex)
{
case 1:
Console.WriteLine("Wrong, try again? [Y or N]");
AskUser();
break;
case 2:
Console.WriteLine("The answer was incorrect");
AskUser();
break;
default:
Console.WriteLine("You can do better than that");
AskUser();
break;
}
static void AskUser() {
string jaellernei = Console.ReadLine().ToUpper();
if (jaellernei == "Y")
{
goto Start;
} else
{
return;
} }
}
}
}
}
Firstly, your AskUser method is incorrectly nested inside the other method - move it out.
Secondly: goto is only valid within a single method; you can jump around a single stack frame - you cannot jump between stack frames.
Thirdly: the number of times you should be using goto... well, it isn't quite zero, but it asymptotically approaches zero.
Don't use goto unless you MUST to !
and As #Marc Gravell said, it's valid within a single method.
Alternatively : you can make a method of the code u used in the Main method, and then call it from both, main method and the other method where you used goto statement.
Like :
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
someFunction();
}
static void someFunction()
{
Random numberGenerator = new Random();
int num1 = numberGenerator.Next(1, 11);
int num2 = numberGenerator.Next(1, 4);
Console.WriteLine("What is " + num1 + " times " + num2 + "?");
int svar = Convert.ToInt32(Console.ReadLine());
if (svar == num1 * num2)
{
Console.WriteLine("well done!");
}
else
{
int responseIndex = numberGenerator.Next(1, 4);
switch (responseIndex)
{
case 1:
Console.WriteLine("Wrong, try again? [Y or N]");
AskUser();
break;
case 2:
Console.WriteLine("The answer was incorrect");
AskUser();
break;
default:
Console.WriteLine("You can do better than that");
AskUser();
break;
}
}
}
static void AskUser()
{
string jaellernei = Console.ReadLine().ToUpper();
if (jaellernei == "Y")
{
someFunction();
}
else
{
return;
}
}
}
}
You could do it like this
public static Random randd = new Random();
public static void FlachCards()
{
Start:
if (AskAUser() == "Y")
{
goto Start;
}
}
public static String AskAUser()
{
Console.WriteLine("Enter Y to play again");
return Console.ReadLine();
}

Return to a specific block of code in my application

I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.

Returning to Main when using an interface in C#

So I've created a blackjack game using an interface whose entry point is "PlayGames()". However, once the game is finished, I want to give the option to the user to go back to the main menu, which is in Main(). Is there a way to call main so that the user can go back to the main menu? Simply calling Main() does not work.
Here's what I've got:
public void PlayGames ()
{
String replay = "";
var a = PlayBlackjack (r, replay);
Console.WriteLine ();
while (a == "yes") {
a = PlayBlackjack (r, replay);
if (a == "no") {
Console.WriteLine ("Okay, goodbye!");
return;
}
}
if (a == "z") {
Main ();
}
}
The variable a is the string user-entered string that determines if the game closes, or continues to play. If the user enters that they want to go back to the main menu, the letter "z" is assigned to a, which will lead them back to the main menu.
Here's what Main() looks like, including class information. The error message that comes up says "Main does not exist in the current context":
using System;
using System.IO;
using System.Collections.Generic;
namespace IntroCS
{
public class PlayCasino
{
private static Random rand = new Random();
private static List<Casino> games;
public static void Main()
{
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
int n = UIF.PromptInt ("Please enter an integer to choose your game: ");
games = new List<Casino> ();
games.Add (new HelpMenu ());
games.Add (new BlackJack ());
games.Add (new QuarterGame ());
if (n == 0) {
Console.WriteLine ("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
}
if (n == 1) {
Console.Clear ();
Console.WriteLine ("Playing Blackjack!" + "\n");
games [0].PlayGames (); //ensures user will get blackjack
}
if (n == 2) {
Console.Clear ();
Console.WriteLine ("Playing the Quarter Game!" + "\n");
games [1].PlayGames (); //ensures user will get quartergame
}
while (n != 0 && n != 1 && n != 2) {
Console.WriteLine ("Try another game!");
n = UIF.PromptInt ("Please enter an integer: ");
}
}
}
}
I would recommend you to put displaying menu & getting input into a function. Just to make it easy to comprehend. Also in your list of games, maybe you want to keep track of game history? if so you need to keep adding a new one like so:
using System;
using System.IO;
using System.Collections.Generic;
using ConsoleApplication8;
namespace IntroCS
{
public class PlayCasino
{
private static Random rand = new Random();
private static List<Casino> games = new List<Casino>();
private static const int INVALID_CODE = -111;
private static const int EXIT_CODE = 4;
public static void Main()
{
int choosen = INVALID_CODE;
while (choosen != EXIT_CODE)
{
switch (choosen)
{
case INVALID_CODE:
choosen = DisplayMenu();
break;
case 0:
displayHelp();
choosen = INVALID_CODE;
break;
case 1:
games.Add(new BlackJack());
games[games.Count-1].PlayGames();
break;
case 2:
games.Add(new QuarterGame());
games[games.Count-1].PlayGames();
break;
default:
DisplayMenu();
break;
}
}
}
private static void displayHelp()
{
Console.WriteLine("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
}
private static int DisplayMenu()
{
Console.WriteLine("MAIN MENU");
Console.WriteLine("(0 for help)");
Console.WriteLine("(1 for blackjack)");
Console.WriteLine("(2 for Quarter Game)");
Console.WriteLine("Please enter an integer to choose your game: ");
string input = Console.ReadLine();
int number;
if (Int32.TryParse(input, out number))
return number;
else
{
Console.WriteLine("Please Try an Integer");
return INVALID_CODE;
}
}
}
}
Your while is repeating the wrong stuff:
public static void Main()
{
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
int n = UIF.PromptInt ("Please enter an integer to choose your game: ");
games = new List<Casino> ();
games.Add (new HelpMenu ());
games.Add (new BlackJack ());
games.Add (new QuarterGame ());
while (n != 0 && n != 1 && n != 2) {
if (n == 0) {
Console.WriteLine ("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
}
if (n == 1) {
Console.Clear ();
Console.WriteLine ("Playing Blackjack!" + "\n");
games [0].PlayGames (); //ensures user will get blackjack
}
if (n == 2) {
Console.Clear ();
Console.WriteLine ("Playing the Quarter Game!" + "\n");
games [1].PlayGames (); //ensures user will get quartergame
}
Console.WriteLine ("Try another game!");
n = UIF.PromptInt ("Please enter an integer: ");
}
}
Notice you never left the "Main" function, so in your "PlayGames" function you can just go ahead and return:
public void PlayGames ()
{
String replay = "";
var a = PlayBlackjack (r, replay);
Console.WriteLine ();
while (a == "yes") {
a = PlayBlackjack (r, replay);
if (a == "no") {
Console.WriteLine ("Okay, goodbye!");
return;
}
}
//Do nothing, the while in Main function will already take us back to the menu
}

C# Menu System will not work

I'm not sure how to explain this but I'll try my best since I'm new to c# programming.
I have created a Menu System
string sChoice;
//Menu
Console.WriteLine("1 - Instructions");
Console.WriteLine("2 - New User");
Console.WriteLine("3 - Record & Score");
Console.WriteLine("4 - Exit System");
Console.Write("Please enter your choice between 1-4: ");
sChoice = Console.ReadLine();
Pressing 1 will then take you to the instructions section of the console application and so on.
//Instructions
if (sChoice == "1")
{
Console.WriteLine();
Console.WriteLine("*Instructions*");
Console.WriteLine();
I have tried an else statement which will repeat the menu and prompt the user of an invalid key, however this will only repeat itself another 3 times before closing. Is there a way for me to block any other keys other than 1-4 being entered or a solution to my problem
Because as it seems, if any key other than 1-4 is pressed then the console application will simply close.
This question remembers me when I was young and started programming.
Maybe you want someting like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
int mainMenuOption = OptionMenu("Instructions", "New User", "Record & Score", "Exit System");
switch (mainMenuOption)
{
case 1: Instructions(); break;
case 2: NewUser(); break;
case 3: RecordAndScore(); break;
case 4: Console.WriteLine("Goodbye.."); return;
}
}
}
static void Instructions()
{
// Handle Instructions here
Console.WriteLine("Instrucctions done");
}
static void NewUser()
{
// Handle New User here
Console.WriteLine("New user done");
}
static void RecordAndScore()
{
// handle recorde and score here
Console.WriteLine("Record & score done");
}
static int OptionMenu(params string[] optionLabels)
{
Console.WriteLine("Please Choose an option");
for (int optionIndex = 0; optionIndex < optionLabels.Length; optionIndex++)
{
Console.Write(optionIndex + 1);
Console.Write(".- ");
Console.WriteLine(optionLabels[optionIndex]);
}
while (true)
{
var input = Console.ReadLine();
int selectedOption;
if (int.TryParse(input, out selectedOption) && selectedOption > 0 && selectedOption <= optionLabels.Length)
{
return selectedOption;
}
else
{
Console.WriteLine("Invalid option, please try again");
}
}
}
}
}

Categories