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.
Related
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.
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;
}
}
}
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...
I've created a small application that does a small conversion. At the end of the program I've created a method that allows the user to make another calculation if they press 'r'. All I want it to do is if they press r, take them back to the beginning of Main, else terminate program. I do not want to use goto. This is what I've got so far, and the error I'm getting.
http://puu.sh/juBWP/c7c3f7be61.png
I recommend you use another function instead of Main(). Please refer to the code below:
static void Main(string[] args)
{
doSomething();
}
public static void WouldYouLikeToRestart()
{
Console.WriteLine("Press r to restart");
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine();
if (input.KeyChar == 'r')
{
doSomething();
}
}
public static void doSomething()
{
Console.WriteLine("Do Something");
WouldYouLikeToRestart();
}
A while loop would be a good fit, but since you say the program should run and then give the user the option to run again, an even better loop would be a Do While. The difference between while and Do While is that Do While will always run at least once.
string inputStr;
do
{
RunProgram();
Console.WriteLine("Run again?");
inputStr = Console.ReadLine();
} while (inputStr == "y");
TerminateProgram();
In your case, you want to repeat something so of course you should use a while loop. Use a while loop to wrap all your code up like this:
while (true) {
//all your code in the main method.
}
And then you prompt the user to enter 'r' at the end of the loop:
if (Console.ReadLine () != "r") {//this is just an example, you can use whatever method to get the input
break;
}
If the user enters r then the loop continues to do the work. break means to stop executing the stuff in the loop.
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();
}