Switch for cinema program (are you sure option) - c#

I am writing a cinema program for my college course.
A menu is required (switch statement), I want to implement a "Are you sure option" with "Yes" and "No" options, where the user enters "Y" or "N" at the end of the program before they place the booking. However I am unsure how to add this within my current code.
Console.Write("Number of Tickets: "); // Oupts "Number of Tickets" to the console window.
int numberOfTickets = 0; // Variable for the user to input how many tickets they want and converts it to a int.
Booking Booking1; // Variable so Booking1 can be linked to the Booking class to be used for the NumberOfTickets.
while (numberOfTickets == 0)
{
if (int.TryParse(Console.ReadLine(), out numberOfTickets)) // Checks to see if user enters valid character.
{
if (Selection.getSeatsAvailable() > numberOfTickets) // If statement so the program knows if there are enough tickets left.
{
Booking1 = new Booking(Selection, numberOfTickets); // If enough tickets program will make a new booking (Booking1) which includes the Selection and the NumberOfTickets.
Selection.updateSeatsAvailable(numberOfTickets); // Updates how many tickets are available for that showing.
Console.Clear(); // Clears the console window.
Console.Write(Booking1.toString()); // Outputs the Booking1 variable, including the Film selected and the number of tickets.
break; // Stops the program.
}
else
{
Console.WriteLine("Showing Full. Select another showing"); // Outputs "Showing Full" to the console window.
numberOfTickets = 1;
continue;
}
}
else
{
Console.WriteLine("please input valid number: ");
continue;
}
}
}
Console.Read();
}
Hope this make sense and thanks for any help...

Related

Making a basic console c# application with a menu based on the key that is pressed

I'm trying to make a program which has two options based on the key is pressed by the user, it'will execute a different action. The second option has to do to displaying some information about operations performed in the first option. The main point is to try to make a navigation menu that the user can come back to the main menu through pressing "ESC" or "Enter" to continue in whatever he chooses
Console.WriteLine("\nCAMPAIGN 2022\nSelect what you want to consult:\n1) Votin Urn\n2) DataBase"); // to make clear, database will display info about votes quantity
int options = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("----------------------");
if (options == 1)
{
ConsoleKeyInfo menu;
Console.WriteLine("\nVOTING URN");
while (exit == false)
{
Console.WriteLine("\nSelect your vote:\n1) Jair Bolsonaro;\n2) Luiz
Inacio Lula da Silva;\n3) White;\n4) NulL");
vote = Convert.ToInt32(Console.ReadLine());
while (vote != 1 & voto != 2 & vote!= 3 & vote != 4)
{
if (increment == 0)
{
Console.WriteLine("\nInvalid Vote. Try again:");
}
vote = Convert.ToInt32(Console.ReadLine());
increment += 1;
The thing is: i'm using an if statement and because of local scope when the user selects option 2, to know who have more votes for example, the value is gonna be 0. I tried using switch but it's the same thing. What can I do?
Also, when the user press "ESC" to come back to select "Voting Urn" or "Database" the first letter of the text displayed is cut, like instead of "Campaign" it's "ampaing". I'm using the ConsoleKeyInfo:
Console.WriteLine("Press \"Enter\" to continue or \"Escape\" to return to the main menu");
menu = Console.ReadKey();
if (menu.Key == ConsoleKey.Escape)
{
exit = true;
}
if (menu.Key == ConsoleKey.Enter)
{
exit = false;
}
I would put the while loop so it covers the menu aswell and then just add another choice that is "Go back to main menu / exit application" in a swtich statement. And then have everything inside that switch statement and maybe do some fucnctions like TotalVotes() and Vote().Then do create variable names with each person you can vote for and just ++ each variable inside an if statement if they get a vote. Also this is probably a typo? "voto != 2". It seems like your structure is making it harder that it has to for you.

Trying to make a menu that keeps repeating if the user enters something invalid

Total beginner here, literally started learning programming for the first time in my life yesterday, so please don't judge!
I'm trying to make a program that allows the user to enter the name and score of videogames, then show these scores upon request. I'm trying to make a menu. I noticed the program would crash if the user presses enter without entering any number, and I wanted to avoid that, but I'm stuck. If I press enter it doesn't crash. However, if I enter 1 or 2, the menu keeps going anyways, and if I press enter without entering anything after that, then it crashes? I'm lost.
namespace videogaems
{
class Program
{
static void Main(string[] args)
{
menu();
}
static void menu()
{
int option = 0;
Console.WriteLine("Select what you want to do: ");
Console.WriteLine("1- add game");
Console.WriteLine("2- show game rating");
bool tryAgain = true;
while (tryAgain)
{
try
{
while (option != 1 || option != 2)
{
option = Convert.ToInt32(Console.ReadLine());
tryAgain = false;
}
}
catch (FormatException)
{
option = 0;
}
}
}
Convert.ToInt32(Console.ReadLine()) will throw an exception if the string cannot be converted to an integer. Instead, you should use int.TryParse, which takes in a string and an out parameter that gets set to the converted value (if successful). It returns a bool which indicates if it was successful or not.
For example, the following code will loop as long as int.TryParse fails, and when it succeeds, userInput will contain the converted number:
int userInput;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Please enter a whole number");
}
Another option, however, is to simply use Console.ReadKey(), which returns a ConsoleKeyInfo object that represents the key that the user pressed. Then we can just check the value of the key character (and ignore any keys that are invalid).
For example:
static void Menu()
{
bool exit = false;
while (!exit)
{
Console.Clear();
Console.WriteLine("Select what you want to do: ");
Console.WriteLine(" 1: Add a game");
Console.WriteLine(" 2: Show game rating");
Console.WriteLine(" 3: Exit");
ConsoleKeyInfo userInput = Console.ReadKey();
Console.WriteLine();
switch (userInput.KeyChar)
{
case '1':
// Code to add a game goes here (call AddGame() method, for example)
Console.Clear();
Console.WriteLine("Add a game was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '2':
// Code to show a game rating goes here (call ShowRating(), for example)
Console.Clear();
Console.WriteLine("Show game rating was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '3':
// Exit the menu
exit = true;
break;
}
}
}

Changing characters on the console depending on user keystrokes

What I want to do is to to change the console depending on what the user has pressed.
So I have a console with three options like this:
> Option 1
Option 2
Option 3
Basically, if the user presses the down arrow, the console becomes like this:
Option 1
> Option 2
Option 3
And if the user presses the up arrow, the console goes back to it's initial state.
I know how to read the user's input with Console.ReadKey(), but I don't know how to modify output that is already written.
One last thing is that when the user presses enter, the console does not create a new line, but chooses one of the options and calls a delegate.
This isn't too difficult to achieve using Console.ReadKey and some variables to hold the state of the selected option.
The following code is a very quick and lazy implementation of what you are looking for. Take the time to rewrite it yourself properly - this is to give you an idea of how you could achieve what you are looking for.
static void Main(string[] args)
{
bool IsRunning = true;
int Selected = 1;
while (IsRunning)
{
ConsoleKeyInfo NextKey = new ConsoleKeyInfo();
if (Selected < 1)
Selected = 3;
else if (Selected > 3)
Selected = 1;
Console.Clear();
if (Selected == 1)
Console.Write("> ");
Console.WriteLine("Option 1");
Console.WriteLine();
if (Selected == 2)
Console.Write("> ");
Console.WriteLine("Option 2");
Console.WriteLine();
if (Selected == 3)
Console.Write("> ");
Console.WriteLine("Option 3");
Console.WriteLine();
Console.Write("Choose an option (Q to Quit): ");
while (!(NextKey.Key == ConsoleKey.DownArrow ||
NextKey.Key == ConsoleKey.UpArrow ||
NextKey.Key == ConsoleKey.Q ||
(NextKey.KeyChar >= '1' &&
NextKey.KeyChar <= '3')))
{
NextKey = Console.ReadKey();
}
switch (NextKey.Key)
{
case ConsoleKey.D1:
// Do something
break;
case ConsoleKey.D2:
// Do something
break;
case ConsoleKey.D3:
// Do something
break;
case ConsoleKey.DownArrow:
Selected++;
break;
case ConsoleKey.UpArrow:
Selected--;
break;
case ConsoleKey.Q:
IsRunning = false;
break;
}
}
}
The code will loop whilst the 'Q' key has not been pushed to quit the application.
Pushing the down or up arrow will rotate through the options available.
Upon pushing 1, 2, or 3, you will cause the // Do something lines inside the switch statement to be run. You should here call whatever functionality exists for each of the options.
In order to update the 'menu' with the chosen option, the console output is cleared and then re-output. The correct option is identified via the Selected variable.
There are several other ways to implement the above, some much tidier. I wanted to give you an idea of where to start. I am not saying that this is the best or most tidy solution.
EDIT
A thought occurs - you wanted to use Enter to select the option.
I've modified the code a little to provide that functionality:
while (!(NextKey.Key == ConsoleKey.DownArrow ||
NextKey.Key == ConsoleKey.UpArrow ||
NextKey.Key == ConsoleKey.Q ||
NextKey.Key == ConsoleKey.Enter))
{
NextKey = Console.ReadKey();
}
switch (NextKey.Key)
{
case ConsoleKey.Enter:
// Do something depending on Selected option
switch (Selected)
{
case 1:
// Do something
break;
case 2:
// Do something
break;
case 3:
// Do something
break;
}
break;
case ConsoleKey.DownArrow:
...
Here's a similar approach with a little less code, which hides the cursor and shows our own custom cursor that indicates the selected menu item.
The method takes in a menu header, a list of options for the user to select from, and a cursor character. It prints out the header and an underline, and then each option with 3 spaces before each one. Then we move the cursor to the first option (row index 3 since the header is 0, underline is 1, and blank space is 2), second character, and write a backspace character followed by our cursor (the backspace erases the first character so we can write a new one).
As the user presses keys, we only handle the up and down arrows and the enter key. By passing true to Console.ReadKey(), the user input is "thrown away" and not displayed on the window. This allows us to switch on only the keys we care about.
When they press an arrow key we move the cursor to the second column in the current row, print a backspace and then a space (to erase the old cursor), then move up or down one row, and from the second column we print a backspace and then our cursor character.
When the user presses Enter, we enable the console cursor again and return the row that the cursor was on to indicate which item was selected at that time:
private static int GetMenuChoice(string header, List<string> options, char cursor = '>')
{
// Clear console and hide cursor
Console.Clear();
Console.CursorVisible = false;
// Write our header with an underline
Console.WriteLine(" " + header);
Console.WriteLine(" " + new string('-', header.Length));
Console.WriteLine();
// Write out each option with spaces before it
options.ForEach(option => Console.WriteLine($" {option}"));
// Move to the first option and, from the second character,
// write a backspace and then the cursor symbol
Console.SetCursorPosition(1, 3);
Console.Write($"\b{cursor}");
// Move cursor when user presses arrow keys, and get selection when they press enter
while (true)
{
// Pass 'true' to ReadKey so the input is not written
var input = Console.ReadKey(true);
switch (input.Key)
{
case ConsoleKey.UpArrow:
if (Console.CursorTop > 3)
{
Console.CursorLeft = 1;
Console.Write("\b ");
Console.SetCursorPosition(1, Console.CursorTop - 1);
Console.Write($"\b{cursor}");
}
break;
case ConsoleKey.DownArrow:
if (Console.CursorTop < options.Count + 2)
{
Console.CursorLeft = 1;
Console.Write("\b ");
Console.SetCursorPosition(1, Console.CursorTop + 1);
Console.Write($"\b{cursor}");
}
break;
case ConsoleKey.Enter:
var selection = Console.CursorTop - 3;
Console.CursorVisible = true;
Console.SetCursorPosition(0, options.Count + 4);
return selection;
}
}
}
This can be tested out with a sample ATM menu:
private static void Main()
{
var options = new List<string>
{
"Open a new account",
"Deposit Money",
"Withdraw money",
"Check balance",
"Exit"
};
var selectedItem = GetMenuChoice("ATM Machine", options);
Console.WriteLine($"You selected option: '{options[selectedItem]}'");
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output

How to use a variable to include a few lines of text when called?

i'm not sure i'm asking this correctly, so if i'm making a mistake please please let me know.
I've tried googling and searching stack for a few hours and have not found a result I could understand well enough to impliment (but i did try, honest).
I am trying to make a helper method to insert in to several different places in my code.
This is the method
//Tried several methods (Do, Do While, For, et al) to make an insert code
public Boolean insertFormat()//Method stub
{
Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
Console.WriteLine(title);//prints program title
}
I thought I could call it like so:
while (true)
{
insertFormat;// This is where i'm trying to repeat the lines - i do this several times so i want to include them somehow (conditions vary)
Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
Console.WriteLine(title);//prints program title
Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
suggestAgain = Console.ReadLine().ToLower();
if (suggestAgain != "n") break;
}
I've tried for loop, do, do while, etc. Tried to do as a variable but didn't do any correctly so as it worked. Generally I ended up with an error saying
'not all code paths return a value'.
I do the clear and reprint the title about 6 times and don't want to have redundant code in my program as I'm told that is not good practice.
Remove the return type (Boolean) from insertFormat method, since you are not returning anything and compiler gives an error. Change it to void
public void insertFormat()//Method stub
{
Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
Console.WriteLine(title);//prints program title
}
// Calling code
while (true)
{
insertFormat();// This is where i'm trying to repeat the lines - i do this several times so i want to include them somehow (conditions vary)
// Skip them, insertFormat will execute them
//Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
//Console.WriteLine(title);//prints program title
Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
suggestAgain = Console.ReadLine().ToLower();
if (suggestAgain != "n") break;
}
You had several errors in your code. Here is working version.
public void insertFormat()
{
Console.Clear();
Console.WriteLine(title);
}
while (suggestAgain != "n")
{
insertFormat();
Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
suggestAgain = Console.ReadLine().ToLower();
}

C# Basic ATM, control flow of menu display

Trying to make a basic ATM program for my C# class.
In short, the program has 4 accounts which have integer values stored already. The program must display first what action the user would like to take (Display balance, Withdraw, Transfer), then take the user to selected menu and be allowed to perform whatever tasks they wish within the program.
Just having problems with my Display Balance menu. Want to ask if the user would like to display another balance, and restart the Display Balance menu section(The code section here). Here is what I have:
if (ACCselect == 1)
{
string yesno1 = " ";
int dispSEL = 1;
Console.WriteLine();
Console.WriteLine("$$$===Display Balance===$$$");
Console.WriteLine();
Console.WriteLine("\t 1) Savings Account");
Console.WriteLine("\t 2) Debit Card Account");
Console.WriteLine("\t 3) Credit Card Account");
Console.WriteLine("\t 4) Investment Account");
Console.WriteLine();
Console.Write("Select account with 1-4: ");
dispSEL = int.Parse(Console.ReadLine());
DisplayBalance(dispSEL);
Console.WriteLine();
Console.Write("Would you like to select another account? (y/n): ");
yesno1 = Console.ReadLine();
if (yesno1.ToUpper() == "Y")
{
yesno1a = true;
}
else
{
Main();
}
} while (yesno1a == true)
This is part of Main(). ACCselect refers to the selection the user makes, whether they want Display Balance, Withdraw, etc.
The DisplayBalance() method selects the appropriate integer value from an array and displays the corresponding balance.
How can I get my program to repeat this section of code if the user selects "y"?
If the user selects "n" it loops back to the top of the Main() method alright.
Any help would be super helpful.
I'm answering this because I did a similar thing in my first year, and I made similar mistakes.
First, you are calling Main in order to "jump" to the beginning of Main. That works, but it gives you nested calls to Main. Main has become recursive. Once you exit the inner Main invocation, you will jump to the outer Main which is still running. Try answering "n" and then try to exit the program. You will have to exit twice.
If you want to repeat an action until a condition is true, you can use this pattern:
while(true) { //loop forever
if (SomeCondition()) break; //exit
else {
DoStuff();
}
}
Applied to your problem, it goes like this:
while(true) { //loop forever
dispSEL = int.Parse(Console.ReadLine());
DisplayBalance(dispSEL);
Console.Write("Would you like to select another account? (y/n): ");
yesno1 = Console.ReadLine();
if (yesno1 == "n") break; //exit
else continue; //next loop iteration
}
Hope that helps. Feel free to ask follow-up questions in the comments.

Categories

Resources