C# How Do I parse variable? - c#

//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

Related

C# Conditions statement

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

How to check for a double type response in an if statement

I'm trying to check if the user's response is a double or an int, but the int is specific, whereas the double is not, as I probably made a right mess of explaining it, here's the code:
Console.WriteLine("\n 2) Q: How old is Sally? \n");
int nSallyAge = Convert.ToInt32(Console.ReadLine());
double dSallyAge = Convert.ToDouble((nSallyAge));
if (nSallyAge == 62 || dSallyAge == 62.0)
{
// Increase Score
sUser1Score++;
Console.WriteLine("\n A: Correct, Sally's age is 62, you have been awarded 1 point. \n");
Console.ReadLine();
}
What I'm trying to do, is instead of dSallyAge HAS to equal 62.0, it just has to equal any double figure.
I would approach this problem by first creating a method that gets a double from the user (that will, of course, also accept an int). This removes error handling from your main code.
NOTE in the code below, Math.Truncate can be replaced by Math.Floor, with the same result:
private static double GetDoubleFromUser(string prompt)
{
double input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again.");
}
return input;
}
Then, in my main code, I would get the number from the user, and use the Math.Truncate method to just read the first part of the double passed in by the user (this is what it sounds like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, it will truncate the result to '62':
double nSallyAge = GetDoubleFromUser("2) Q: How old is Sally? ");
if (Math.Truncate(nSallyAge) == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Other alternative ways to use this are:
int sallyAge = Math.Truncate(GetDoubleFromUser("2) Q: How old is Sally? "));
if (sallyAge == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Or, you could use an input function that returns an int in the first place:
private static int GetIntFromUser(string prompt)
{
return Math.Truncate(GetDoubleFromUser(prompt));
}
In your code above, you are converting the input to an integer and then converting the int result to a double.
Assuming that you are only allowing numerical values to be entered, why not try something like this. This will identify if the input contained decimals or not:
string input = Console.ReadLine();
int iSallyAge;
double dSallyAge;
if (!Int32.TryParse(input, iSallyAge))
{
dSallyAge = Double.Parse(input);
}
You should be using Double.TryParse to parse the user input to a double and then test that value to see whether it's equal to 62.0.
double age;
if (double.TryParse(Console.ReadLine(), out age) && age == 62.0)
{
// age is 62.
// ...
}

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.

If else Statment not working

Hi my If statement wont work for some reason I want it to say invalid if user goes below 0 or over 100 but every number i put in goes directly to my else statement doesn't even notice my if statement.
What am I doing wrong?
g:
Console.WriteLine("Enter Grade: ");
int grade = Convert.ToInt32(Console.Read());
if (grade < 0 || grade > 100)
{
Console.WriteLine("Input Valid");
Console.ReadLine();
}
else
{
Console.WriteLine("Input invalid");
Console.ReadLine();
}
goto g;
if/else is not a problem here. The way you're getting input from user is.
Use Console.ReadLine() instead of Console.Read():
int grade = Convert.ToInt32(Console.ReadLine());
Console.Read returns numeric representation (ACII code) of the first character from console, not the number you've typed itself.
Some changes you might need to do:
int grade = Convert.ToInt32(Console.ReadLine());
and change your condition to &&:
if (grade >= 0 && grade <= 100)
Change your read statement as follows:
int grade = Convert.ToInt32(Console.ReadLine());
Console.Read() returns the ASCII code that you typed, while Console.ReadLine() returns a string.

Reask for User Entry or Continue the code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Facing this problem all the time but couldn't really figure out how to overcome with it;
It is related with the user entry - in case the user enters something wrong I want the program to continue or reask the question;
an example ;
I want the user to enter the age
when the user enters the age correctly I want the program to continue (but in below code it asks 5 times
if the user enters a wrong entry (i.e string) I want the program to reask to enter the age
Vm appreciate to hearing your kind assitance
for (int i = 0; i < 5; i++)
{
int _Age;
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if (!AgeCheck)
{
Console.WriteLine("Please enter your age : ");
}
else
{
i--;
continue;
}
}
int age = 0;
while (true)
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
if (int.TryParse(entry, out age)) break;
}
The idea is simply to run an "infinite" loop until a valid age is entered, at which point we break out of the loop.
Instead of the infinite loops:
int age = 0;
do
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
} while (!int.TryParse(entry, out age));
Nothing wrong with the infinite loop inherently. I just think it's cleaner without.
infinite loop, just issue a "break;" and it will drop out....
int _Age;
while( true )
{
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if ( AgeCheck == true ) { break; }
}
Answer to your question about the question being asked 5 times. You have a for loop that will spin through the code 5 times regardless of the answer the user gives.
for (int i = 0; i < 5; i++)
{ your code is here }
In the code below, after the do loop, you'll have the input from the console in the answer variable and the parsed int in the age variable. You can create a new console app in VS and paste this into Program.cs and run it to test.
using System;
namespace console {
internal class Program {
private static void Main( string[] args ) {
int age;
string answer;
do {
Console.Clear();
Console.Write( "Please enter your age: " );
answer = Console.ReadLine();
} while ( !int.TryParse( answer, out age ) );
Console.WriteLine( string.Empty );
Console.WriteLine( "Thanks, let's continue..." );
Console.Read();
}
}
}

Categories