C# Conditions statement - c#

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");
}
}

Related

C# How can I make an exception to allow only numbers?

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.");
}

c# cant run two functions in a loop?

What i want to do is to make it that inside a loop, the computer checks whether the number entered is firstly not a decimal, and at the same time i want to make sure that the number is within the range 1 - 100. My code now works in regards to having the first function about the number not being a decimal, so when i enter a decimal, an error message is displayed that tells the user to keep adding another number until an integer is added, and it then runs to the next part. However it doesn't seem to work when i put in a number outside of the range, the error message doesn't pop up and the conditions just don't seem to work. What i want to know is how do i get these two parts, the decimal and the range checking to work simultaneously. I'm really new to coding so could any explanations be simple so that i could understand. Thank you in advance!
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = int.TryParse(inputcost, out validcost);
while (!int.TryParse(inputcost, out validcost))
{
if (result == true )
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("You Cannot Enter Decimals. Please Enter A Valid Integer Value.");
Console.WriteLine();
inputcost = Console.ReadLine();
}
if (validcost < 100 && validcost > 1)
{
Console.Write("valid value");
}
else
{
Console.Write("invalid value.please enter a number between 1 and 100 ");
Console.ReadLine();
}
}
The line
while (!int.TryParse(inputcost, out validcost))
means that you enter the while loop only when the user types something that cannot be converted to an integer. If it is a valid integer the code inside the while loop is never reached and thus, your test on the valid range is never executed
Instead put everything inside the an infinite loop and provide a way to break the program (type x to quit)
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: (type x to quit)");
inputcost = Console.ReadLine();
// Check if the user wants to stop executing the program
if(inputcost == "x")
break;
// Check if it is a valid integer
bool result = int.TryParse(inputcost, out validcost);
if (!result)
{
Console.WriteLine("You Cannot Enter Decimals (or strings). Please Enter A Valid Integer Value.");
}
else if (validcost > 100 || validcost < 1)
{
Console.WriteLine("invalid value.please enter a number between 1 and 100 ");
}
else
{
Console.WriteLine("Valid value");
// other code block that works with the input number....
}
}
Alternativly use another condition for your loop, something that first checks for an integer and afterwards if it is in range:
while (!int.TryParse(inputcost, out validcost)) || validCost < 1 || validCost > 100)
{
Console.WriteLine("Please enter an integer between 1 and 100");
inputCost = Console.ReadLine();
}
All the code that should be executed when your inout is valid should now gow beyond the loop, not inside it.

Programme Qutting on user input of text instead of integer value

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.

Finding it difficult with the following code [closed]

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.

C# How Do I parse variable?

//Prompts user for their age
int age;
ApplicationUtilitiesinternal.DisplayDivider("Get Age");
Console.WriteLine("What is your age? ");
while (!int.TryParse(Console.ReadLine(), out age)) //Makes sure the user inputs a number for their age
Console.WriteLine("You did not enter a valid age - try again.");
age = InputUtilities.GetInput("Age");
I know I need to parse the variable, age, but I'm not sure how to do it. I've tried several methods and searched the web for answers. Just when I think I had it...another error would pop up. I know this should be simple.
Edit:
Okay, I'm going to add some context here. Here's what I have to call from:
class InputUtilities
{
internal static string GetInput(string inputType)
{
Console.WriteLine("Enter your " + inputType);
string strInput = Console.ReadLine();
return strInput;
}
}
I hope this makes more sense now.
To answer your actual question: "I know I need to parse the variable, age, but I'm not sure how to do it.", as already stated by others, you ARE doing it.
I've ignored your ApplicationUtilitiesinternal and InputUtilities classes as they don't appear to be relevant to your requirement, along with the fact that InputUtilities.GetInput() returns a string and you are trying to assign it to an int (age).
I suggest this code should make things clearer:
Console.WriteLine("Please enter your age (1-120):");
int nAge;
while(true)
{
string sAge = Console.ReadLine();
if(!int.TryParse(sAge, out nAge))
{
Console.WriteLine("You did not enter a valid age - try again.");
continue;
}
if(nAge <= 0 || nAge > 120)
{
Console.WriteLine("Please enter an age between 1 and 120");
continue;
}
break;
}
// At this point, nAge will be a value between 1 and 120

Categories