How to exit the program if exit option is selected? [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Good evening.
Apologies for the noob question, I am new to C# so I'm still getting to grips with a few things. I am trying to write a simple program as shown below, but I'm struggling to get the coding correct for the exit function. How can I write this code to exit to program if the exit option is input, as 'if choice ==4' does not seem to work?
// Demonstrate branching and loops.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fundamentals
{
class Program
{
static void Main(string[] args)
{
do
{
// Example: Switch.
Console.WriteLine("Main Menu");
Console.WriteLine("1 - Play. ");
Console.WriteLine("2 - Options. ");
Console.WriteLine("3 - Help. ");
Console.WriteLine("4 - Exit. ");
Console.WriteLine(" ");
int choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("Playing the game.");
Console.WriteLine("");
// Example: do... while loop.
double ans;
do
{
Console.Write("What is: 10 x 10 = ");
ans = Convert.ToInt32(Console.ReadLine());
} while (ans != 100);
Console.WriteLine("\nCorrect!\n");
break;
case 2:
Console.WriteLine("Game settings.\n");
break;
case 3:
Console.WriteLine("Game Help.\n");
break;
case 4:
Console.WriteLine("Exiting...\n");
break;
default:
break;
}
if (choice == "4")
{
Environment.Exit(0);
}
} while (true);
}
}
}

choice is an int and you're comparing it to a string - so
if (choice == 4)
{
Environment.Exit(0);
}
for the code you posted- but you could just put the exit code in the case:
case 4:
{
Console.WriteLine("Exiting...\n");
Environment.Exit(0);
break;
}

You would've saved yourself from having this problem by putting your Environment.Exit() call inside the switch statement that is correctly comparing two int's, rather than re-evaluating a condition after evaluating the conditions...
Those that said int is never equal to string are on the money, but if I may suggest an even more correct solution you shouldn't have that if statement at all.
switch (choice)
{
case 1:
Console.WriteLine("Playing the game.");
Console.WriteLine("");
// Example: do... while loop.
double ans;
do
{
Console.Write("What is: 10 x 10 = ");
ans = Convert.ToInt32(Console.ReadLine());
} while (ans != 100);
Console.WriteLine("\nCorrect!\n");
break;
case 2:
Console.WriteLine("Game settings.\n");
break;
case 3:
Console.WriteLine("Game Help.\n");
break;
case 4:
Console.WriteLine("Exiting...\n");
Environment.Exit(0); //// Just exit from here...
default:
break;
}

Related

How do I add a Y/N to Switch-Cases in C#?

I'm a complete Newbie to the world of programming, yet I really wish to learn a lot as quick as possible and now came up to a problem that I can't find to solute just via researching and "learning- by doing" (Trying around).
Basically I'm trying to work on a small console- based TextAdventure in C Sharp (With VisualStudios) Now I came to a Case- Switch (Offering the User some Options to read and walk through), but I wish to add a Y/N Confirmation in case the User decides to take a different path. For now it's only for the starting point of the story:
Does the User want to go into "The Wilds", "The City", "The Farm". Something as simple as that just in addition: "Are you sure (Y/N)?" leading the No to return the given choices.
Thank you all in advance and stay healthy!
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
private void TakeYourLeave()
{
WriteLine("\nYou are about to take your leave... Are you sure ? (Y/N)");
ReadKey();
Environment.Exit(0);
}
private void VisitTheMemorial()
{
Clear();
//FILLER//
WriteLine("You may proceed by the press of any button.");
ReadKey(true);
RunMainMenu();
}
private void EnterTheWorld()
{
string prompt = "Where would you like to start your journey?";
string[] options = { "The Slums", "The Wilds", "The City", "The Farm" };
Menu startMenu = new Menu(prompt, options);
int selectedIndex = startMenu.Run();
BackgroundColor = ConsoleColor.White;
switch (selectedIndex)
{
case 0:
ForegroundColor = ConsoleColor.Black;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 1:
ForegroundColor = ConsoleColor.Green;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 2:
ForegroundColor = ConsoleColor.Red;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 3:
ForegroundColor = ConsoleColor.Yellow;
WriteLine("\n ||Small Description|| Are you sure to take this path? (Y/N)");
break;
}
In this case, you need to take care of a few things:
Make sure that the entire switch-statement logic is in a while-loop, as such:
while (True) {
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
Check with your function if the input given is "No", if such, then immeditely return so your function exits before any navigation
private void VisitTheMemorial()
{
userInput = readKeyFunction();
if (userInput == "no") {
return;
}}
Finally, if the user doesn't select no, just do nothing and let the function go on
It is best to handle the 'Are you sure?' inside the menu.Run(), and return a value to the selectedIndex after the confirmation. Also avoid using while loop at the main flow in this case.
Note: you have to think in a modular way. Consider your Menu class as a module which handles user choice. The main flow does not have to bother about the confirmation by the user, it just have to process the final result of the user.
Another suggestion: Use enums instead of integers wherever possible for multiple choices.

breaking out a loop in c#

I am having trouble figuring out how to break out of a loop that contains a switch statement.
i need to press 0 twice to exit the console why?
how can i fix it to exit from the first time
public void Start()
{
int choice = 0;
bool trueNumber = false;
do
{
ShowMenu(); // display the menu
Console.Write("Your Choice : ");
trueNumber = int.TryParse(Console.ReadLine(), out choice);
if (!trueNumber)
Console.WriteLine("Your Choice must be an integer. Try again.");
switch (choice) // select the relevant function based on user input
{
case 1:
CalculateCelsiusToFahrenheit();
break;
case 2:
CalculateFahrenheitToCelsius();
break;
case 0:
return; // exit when i press 0
default:
Console.WriteLine("Invalid Option: Choose 0, 1, or 2 Thank you ");
break;
}
} while (choice != 0);
}
If you are running this from an IDE (like Visual Studio), the default behavior for console applications is to end with a "Press any key to continue." so it waits with the output displayed.
related answer: VS setting

Variables in C# [duplicate]

This question already has answers here:
Use a variable from another method in C#
(2 answers)
Closed 2 years ago.
I've been searching for answers to solve this tiny bit of code, but without luck. I figure I have to declare the variable for "item" outside the method, but I can't seem to find a way to do so.
beginner
namespace Items
{
class Program
{
static void Main(string[] args)
{
bool myBool = true;
while (myBool)
{
Console.WriteLine("Welcome");
Console.WriteLine("[1] - add item");
Console.WriteLine("[2] - see content");
Console.WriteLine("[3] - erase content");
Console.WriteLine("[4] - close");
int input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("add item");
var item = (Console.ReadLine());
Console.WriteLine("you just added: " + item);
break;
case 2:
Console.WriteLine("items added: " + items);
break;
case 3:
myBool = false;
break;
}
}
}
}
}
welcome to Stack Overflow! It's not quite clear what you're asking here - questions should typically include what you expect the code to do, and what it actually does. That said, I think I can see what you're going for. I've updated the code, and added some comments to describe the changes.
using System;
using System.Collections.Generic; // This namespace contains the 'List<>' class
namespace Items
{
class Program
{
static void Main(string[] args)
{
// I've moved this outside of the loop - I assume users would want the help message
// displayed on startup, not every single time they do something.
Console.WriteLine("Welcome");
Console.WriteLine("[1] - add item");
Console.WriteLine("[2] - see content");
Console.WriteLine("[3] - erase content");
Console.WriteLine("[4] - close");
// The list of items is created here, outside of the main loop.
var items = new List<string>();
// You don't need to declare a variable 'myBool' here
// We can just loop until the user exits the whole program
while (true)
{
int input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("add item");
var newItem = Console.ReadLine();
Console.WriteLine("you just added: " + newItem);
break;
case 2:
Console.WriteLine("items added:");
foreach (var item in items)
Console.WriteLine(item);
break;
case 3:
items.Clear();
break;
case 4:
return;
}
}
}
}
}
I would recommend following some tutorials first, so you get an idea of variable scope - how long a variable lives for and where it can be accessed from.
It depends what you're trying to do here. On line 33, do you want to show all the items, or just the previous item to be added?
The error you're getting is that the variable "items" doesn't exist. If you just want to show the previous item to be added, then you can replace the word "items" with "item", and move the line where you declare "item" to outside the switch statement, to look like this:
static void Main(string[] args)
{
bool myBool = true;
var item;
while (myBool)
{
Console.WriteLine("Welcome");
Console.WriteLine("[1] - add item");
Console.WriteLine("[2] - see content");
Console.WriteLine("[3] - erase content");
Console.WriteLine("[4] - close");
int input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("add item");
item = (Console.ReadLine());
Console.WriteLine("you just added: " + item);
break;
case 2:
Console.WriteLine("items added: " + item);
break;
case 3:
myBool = false;
break;
}
Now, we're declaring the variable item in the Main method rather than in the switch statement. Before, when you were declaring it in the switch statement, it was being reset every time you restarted the loop. Now, when the user changes it by inputting a value, it will be saved when you go back to the start of the loop, and so if the user inputs "2", they will be shown the last item they inputted.
If you want the user to be shown every item they have inputted, you'll need to use an array or collection.

Could anyone help me find the error in this simple C# program? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I was just wondering if someone could help me out, I am trying to compile this c# program and csc.exe keeps returning the error
Exercise_.cs<11,25>: error CS1002: ; expected
Though I cannot find a missing semicolon...any help would really be appreciated.
using System;
namespace _8546574 {
class exercise_8 {
static void Main(string[] args){
bool running = true;
While(running = true){
Console.WriteLine("Enter a number between 1 and 3");
Console.Clear();
int input = int.Parse(Console.ReadLine());
switch(input){
case 1:
Console.WriteLine("You entered 1");
running = false;
Console.ReadLine();
break;
case 2:
Console.WriteLine ("You entered 2 :)");
running = false;
Console.ReadLine();
break;
case 3:
Console.WriteLine("You entered 3");
running = false;
Console.ReadLine();
break;
default:
Console.WriteLine("failed");
Console.ReadLine();
break;
}
}
}
}
replace your line While(running = true){ with while(running){ that should work
while must be lowercase and the check can (running) or (running == true)
From your code I just noticed that you have While and it should be while.
while(running == true)
or
while(running)
From copying your code exactly as written, you need to make while lower case, and add an extra } to the end of the code. everything else compiles fine

C# How do I make a switch ignore invalid input?

I am trying to make a simple console game that starts with a title screen. The user inputs 'N' for a new game, 'L' to load a game, or 'E' to exit. I have this set up as a switch, but I need to know how to make the program ignore any input other than the aforementioned keys. I've Googled this question but didn't find an answer. Please help if you can.
I don't see much point in posting the code as 10 lines of a simple switch probably wouldn't be terribly helpful to solving the problem. Also, if there would be an easier / more efficient way than a switch, I would love to know.
Thanks.
You can use a default: statement to handle the other (unknown) cases:
switch(inputString.ToLower())
{
case "n":
// Handle new
break;
//.. handle known cases
default:
Console.WriteLine("Unknown option chosen. Please enter valid option:");
// Re-read values, etc?
break;
}
Anything not specified in one of your other cases will fall into the default case, which you can then use to prompt for valid input.
If you want to actually ignore all keys other than valid ones you could do something like this:
public static char ReadKey(IEnumerable<char> validKeys)
{
var validKeySet = new HashSet<char>(validKeys);
while (true)
{
var key = Console.ReadKey(true);
if (validKeySet.Contains(key.KeyChar))
{
//you could print it out if you wanted.
//Console.Write(key.KeyChar);
return key.KeyChar;
}
else
{
//you could print an error message here if you wanted.
}
}
}
When you use ReadKey(true) the true indicated that it will intercept that key and not display it on the console. This gives you the option of determining if it's valid or invalid.
If a switch statement does not have a default block, and if the expression being switched on does not match any of the case blocks, the switch statement does nothing.
When you have only 3 cases, a switch isn't much more efficient than just a simple if-else construct.
if (input == "N")
{
// New game
}
else if (input == "L")
{
// Load game
}
else if (input == "E")
{
// Exit game
}
// if none of the cases match, the input is effectively ignored.
If you insist on using a switch, then your construct is very similar:
switch (input)
{
case "N":
//New Game
break;
case "L":
//Load Game
break;
case "E":
//Exit Game
break;
default:
//Do nothing (ignore unmatched inputs)
break;
}
Thanks for the replies, guys. I managed to solve the problem by doing the following:
static void titleInput()
{
ConsoleKeyInfo titleOption = Console.ReadKey(true);
switch (titleOption.Key)
{
case ConsoleKey.N:
Console.Clear();
break;
case ConsoleKey.L:
break;
case ConsoleKey.E:
Environment.Exit(0);
break;
default:
titleInput();
break;
}
}
I'm not sure how 'proper' this is, but it does what I need it to do. Any keys other than 'N', 'L', and 'E' no longer do anything.

Categories

Resources