Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written up to this place and am stuck I need help on how to terminate a program or continue .
What I mean is that when I ask the question would you like to withdraw today and if their response is NO then the program should terminate but if its YES it should continue.
What am I missing?
Please implement the aspect where by the program should terminate using the N for NO statement i didn't received the answer to that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
Console.ReadLine();
}
}
}
You are on the right track. What you are missing is to take and evaluate the user input - this is the information returned by the Console.ReadLine method (as mentioned in the comments) like this:
line = Console.ReadLine();
Your code could look like this:
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// save user input
var userInput = Console.ReadLine();
// evaluate if user wants to continue or not
if (userInput.ToLower() == "y")
{
// if yes, go further
Console.WriteLine("continue with other action...");
}
// else bye
Console.WriteLine("goodbye");
The line for the PIN already uses the user input! The same can be done with the question. If you want to stay in the loop until the user does not want to withdraw any more, than you need more than if-else. Take a look at the iteration statements like do and while.
A solution could look like this:
// user input = y or n
string choice;
// user pin
int pin = 0;
// state that indicates if the user wants to continue or not
bool continueLoop = false;
do
{
// greet user
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// take input
choice = Console.ReadLine();
// check if user has entered valid input
if (choice.ToLower() == "y" || choice.ToLower() == "n")
{
// default decision is "user does not want to continue" = exit
continueLoop = false;
// user has choosen to continue
if (choice.ToLower() == "y")
{
// user wants to do something, so stay in the loop
continueLoop = true;
// ask for pin
Console.WriteLine("Enter your pin");
var pinAsText = Console.ReadLine();
// convert the pin to number: if (int.TryParse(pinAsText, out pin)) ...
if (pinAsText == "1234")
{
Console.WriteLine("PIN correct");
// continue with logic here, for example take amount
}
else
{
Console.WriteLine("PIN incorrect");
}
}
}
else
{
Console.WriteLine("Please enter Y or N");
continueLoop = true;
}
} while (continueLoop);
Console.WriteLine("goodbye");
Now the flow looks like this:
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 3
PIN incorrect
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 1234
PIN correct
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> N
goodbye
Certainly when your users have two different choice , you should use if in your program . Also you should save user's answer into a local variable to process it .
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
char answer = char.Parse(Console.ReadLine());
if (answer == 'Y')
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
}
When you write nothing for "no" , your program will terminate .
Also you can use string instead of char :
string answer = Console.ReadLine();
if (answer == "Y")
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
By the way, there are a lot of possible errors in your code (e.g. enter a character instead of integer for variable ' pin ') that must be handled by try-catch.
Related
I'm working on a conditional statement and I'm having difficulty getting my small transportation console application to run properly in Windows Studio 2022. After pressing 1 or 2 (Yes or No) my application goes back to my main menu instead of proceeding to the user choosing a route or choosing not to purchase a ticket.
{
Console.WriteLine("Would you like to buy a Ticket?\n");
Console.WriteLine("Please Type 1 for: Yes");
Console.WriteLine("Please Type 2 for: No");
var response = Console.ReadLine();
Console.WriteLine(response);
int num = 1;
if (num == 1)
{
Console.WriteLine("1) For the first route option, please type 1");
Console.WriteLine("2) For the second route option, please type 2");
}
int num2 = 2;
if (num2 == 2)
{
Console.WriteLine("No Ticket Purchased: Have a great day!");
}
else
{
Console.WriteLine("Your answer was not vaild");
}
I'd expect your code to look something like this -- where you check the response value.
{
Console.WriteLine("Would you like to buy a Ticket?\n");
Console.WriteLine("Please Type 1 for: Yes");
Console.WriteLine("Please Type 2 for: No");
var response = Console.ReadLine();
Console.WriteLine(response);
if (response == '1')
{
// do something to let them buy a ticket
}
else
if (response == '2')
{
Console.WriteLine("No Ticket Purchased: Have a great day!");
}
else
{
Console.WriteLine("Your answer was not vaild");
}
}
You are reading the data in the variable called response and never using it.
You are setting the data in the variable num1 with value 1 and num2 with 2, and you are checking them in the if condition.
You can try to create functions to execute within the if-else blocks to give you better readability over the code.
First , the answers that I see in this page is correct.
it seems that you forgot the using of the response.
But I’m having trouble understanding your question.
You declare response as a var and then you decide to use int.
No problem, you can make it if you want.
But if you want to use int , you need to put it in try-catch block in order to avoid get an exception in case user will enter string.
This exception will get when you convert the var to int.
I add some comments to explain the code.
if you have questions - don't hesitate to ask.
goodluck !
private static void BuyTicket(bool retry = true)
{
int selection = 0;
Console.WriteLine("Would you like to buy a Ticket?\n");
Console.WriteLine("Please Type 1 for: Yes");
Console.WriteLine("Please Type 2 for: No");
var response = Console.ReadLine();
//for case user enter a string and not a number, so need to give friendly message of the options available
try
{
selection = int.Parse(response);
}
catch (Exception ex)
{
Console.WriteLine("Please choose '1' or '2' only");
Console.WriteLine(ex.Message);
if (retry == true)
{
//if the user will enter invalid data this time , it will skip and continue
BuyTicket(false);
}
}
if (selection == 1)
{
Console.WriteLine("You choosed to buy a ticket.");
Console.WriteLine("1) For the first route option, please type 1");
Console.WriteLine("2) For the second route option, please type 2");
response = Console.ReadLine();
Console.WriteLine("Thanks for your choice. You choose " + int.Parse(response) + " route option");
}
else if (selection == 2)
{
Console.WriteLine("No Ticket Purchased: Have a great day!");
}
else
{
Console.WriteLine("Your answer was not vaild. Please enter '1' or '2' only");
}
}
Here is my Code
Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
int userInput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
if (userInput == 1)
{
// Player
Player player = new Player();
I tried to make an try catch block but then I always got a porblem with userInput in my if statement. I want a try .. catch block to make sure, if the user enters a char or somethingelse (+,~,#,...) they get an error message and can enter something new.
I suggest using loop and if instead of catching exceptions (exceptions have been designed for exceptional situations which are not the case - we should validate user input only):
int userInput = -1;
// Keep on asking user until valid input is provided
while (true) {
Console.WriteLine("Do you want to:");
Console.WriteLine(" 1. play against an Ai or ");
Console.WriteLine(" 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
// Trim() - let's be nice and tolerate leading and trailing spaces
string input = Console.ReadLine().Trim();
if (input == "1" || input == "2") {
userInput = int.Parse(input);
break;
}
Console.WriteLine("Sorry, invalid option. Please, try again.");
}
So I wrote a lottery program.
The program works as the following:
the user inputs 6 numbers ranging from 1 to 46.
the program chooses 6 numbers ranging from 1 to 46.
the program compares the arrays for matching numbers.
the program shows the user how many matching number he got right and also if he won the lottery or not.
end
now , I want to add an option to the user , if the user wants to try again he can just press Y and the program will jump him to the point where he inputs numbers.
But , I don't know how to achieve that without using goto, I don't want to use goto because I know it's bad practice to use it.
Would love to get some recommendations.
I know that I am still missing the N portion of the code, but I just wanted to show what I've tried so far.
char tryAgain;
if (gamelost || gamewon == true)
{
tryAgain = 'Y';
Console.WriteLine("Do you want to try again? Y/N");
tryAgain = char.Parse(Console.ReadLine());
if (tryAgain == 'Y')
{
goto gameAgain;
}
else
{
return;
}
}
}
Use a loop. You need to check the only condition upon which you exit the loop. Note that this code doesn't sanitize user's input.
using static System.Console;
void do_lottery()
{
while (true)
{
Write("Enter 6 digits, divided by comma: ");
var input = ReadLine();
var user_numbers = input.Split(",").Select(n => int.Parse(n));
var numbers_to_guess = new[] { 6, 23, 12, 46, 8, 2 };
if (user_numbers.All(n => numbers_to_guess.Any(z => z == n)))
{
WriteLine("You won!");
}
else
{
WriteLine("You lose!");
}
Write("Do you wanna play once again? (Y/N): ");
var answer = ReadLine().ToUpper();
if (answer != "Y") break; //Exit loop
}
WriteLine("Lottery finished.");
}
As you can probably tell from my question, I am very new to coding. I am trying to make a calculator that computes some formulas that are used in physics. However, the code runs the formula before the user has time to enter a value for A, in this example at least. Here is the example:
case "f = ma":
Console.WriteLine("Type the value for M in KG:");
var FM = Console.Read();
Console.WriteLine("Type the value for A in M/S:");
var FA = Console.Read();
var FMARes = FM * FA;
Console.WriteLine("Your answer (in Newtowns) is " + FMARes);
break;
How am I able to check whether a value has been assigned to the variable A, and only run the formula after the variable has an assigned value? Thanks.
You need to use ReadLine instead of Read. You also need to do another ReadLine at the bottom so the user can see the result. And...you should validate that the user entered a valid number. This could be refactored a bit to avoid duplicate code - etc. - but see if this works for you! Good luck!!
static void Main(string[] args)
{
double fm;
double fa;
// Use ReadLine instead of Read
Console.WriteLine("Type the value for M in KG:");
var input = Console.ReadLine();
// Now you need to cast it to a double -
// -- but only if the user entered a valid number
if (!double.TryParse(input, out fm))
{
Console.WriteLine("Please enter a valid number for M");
Console.ReadLine();
return;
}
Console.WriteLine("Type the value for A in M/S:");
input = Console.ReadLine();
if (!double.TryParse(input, out fa))
{
Console.WriteLine("Please enter a valid number for A");
Console.ReadLine();
return;
}
// Now we have valid values for fa and fm
// It's a better programming practice to use the string format
// intead of + here...
Console.WriteLine($"Your answer (in Newtowns) is {fm * fa}");
// You need another read here or the program will just exit
Console.WriteLine("Press Enter to end the program");
Console.ReadLine();
}
Just going through my code and I'm trying to solve an issue when testing for how can I get the programme to stop quitting the console when a user enters an option in the menu in text form for example they want to choose option "1" but decide to type the word "one" instead.
Thanks
Dan
int numNumbersReqd = 5;
int chosenOption = 0;
bool quit = false;
Console.WriteLine("*****************************************************************************");
Console.WriteLine("* This application is designed to allow you to select the number of numbers *");
Console.WriteLine("* you wish to enter, and sum the numbers that you provide. *");
Console.WriteLine("*****************************************************************************");
while (quit == false)
{
DisplayMenu();
chosenOption = ReadNumber("Please choose an option:");
quit = ProcessMenu(chosenOption, ref numNumbersReqd);
}
}
static void DisplayMenu()
{
Console.WriteLine("Select an option");
Console.WriteLine("1. Add numbers");
Console.WriteLine("2. Change amount of numbers to be entered");
Console.WriteLine("3. Quit");
}
static int ReadNumber(string prompt)
{
string text;
int number;
Console.Write(prompt);
text = Console.ReadLine();
number = int.Parse(text);
return number;
}
static bool ProcessMenu(int option, ref int numNumbers)
{
bool quit = false;
switch (option)
{
case 1:
int total;
total = GetTotal(numNumbers);
DisplayResult(total); // Programme was initally set to display the option that the user had entered from "displayMenu", by changing the variabel from option to total it will now display the answer of the numbers entrered by the user
break;
case 2:
numNumbers = ReadNumber("Please enter the number of numbers to be entered:");
break;
case 3:
quit = IsQuitting();
break;
default:
Console.WriteLine("Unknown option value entered");
break;
}
return quit;
}
static int GetTotal(int numbersReqd)
{
int total;
int index;
total = 0;
for (index = 0; index < numbersReqd - 1; index++)
{
total = total + ReadNumber("Please Enter Number:");
}
return total;
}
static void DisplayResult(int total)
{
Console.WriteLine("###############################################################################");
Console.WriteLine("###############################################################################");
Console.WriteLine("################## " + total.ToString() + " ##################");
Console.WriteLine("###############################################################################");
Console.WriteLine("###############################################################################");
}
static bool IsQuitting()
{
string response;
bool quit = false;
Console.Write("Do you really wish to quit?");
response = Console.ReadLine();
response = response.ToLower();
if (response == "yes") // Problem fixed with quit option, "YES" used before was specifying uppercase only inputs which are highly unlikely to be entered by the user which caused the programme to loop back to the start menu,
{
Console.WriteLine("Quiting");
quit = true;
}
return quit;
Use this:
int number;
while (!int.TryParse(Console.ReadLine(), out number)) // make sure that the user enters a valid number
Console.WriteLine("You did not enter a valid number");
// here number will have the value entered by the user.
TryParse will return true or false if the first parameter is a valid integer, and that value gets assigned to the second parameter using the out keyword.
"Regular" Parse will either convert the string to an integer, or throw an exception if it's not a valid integer.
Edit: cFrozenDeath suggested a good edit to my post, which encases the TryParse in a while loop. Effectively, what this is doing, is it will get input from the user UNTIL they enter a valid number. It is generally considered a good idea; if they enter in something incorrectly on accident, you most likely don't want to just immediately quit / end the program.
However, there is no logic in the while condition to also check if the value is "valid" from a requirements stand point. Your menu has 3 options, but if they enter 100 they've entered a mathematically valid integer but not a valid integer for your application. So you might want to also add a condition or two to check that number is within the acceptable range.
You can use use int32.TryParse() instead of int.Parse().
The value will be 0 when the parsing failed and you can then act accordingly.