How to check input is a valid integer [duplicate] - c#

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
I try to tell the user that ,whenever he types in a string instead of an integer, he/she should type in a number.But somehow the code within the if statement never shows up.
private static void Number()
{
Console.Write("Type it in a number: ");
int result = int.Parse(Console.ReadLine());
if (float.IsNaN(result))
{
Console.WriteLine("Please type a number!");
}
else
{
Console.Write("Hi");
}
Console.ReadLine();
}

private static void Number()
{
Console.Write("Type it in a number: ");
int result;
bool parsedSuccessfully = int.TryParse(Console.ReadLine(), out result);
if (parsedSuccessfully == false)
{
Console.WriteLine("Please type a number!");
}
else
{
Console.Write("Hi");
}
Console.ReadLine();
}

You can do by int.TryParse for that
private static void Number()
{
Console.Write("Type it in a number: ");
int result;
if (int.TryParse(Console.ReadLine(), out result))
{
// user input a valid integer
// result varaible have the input integer
Console.Write("Hi");
}
else
{
// user input none integer
Console.WriteLine("Please type a number!");
}
Console.ReadLine();
}

Try using TryParse method to validate the entered string , you can also use
int.TryParse
Code :
private static void ValidateInput() {
Console.Write("Type the number: ");
string userInput = Console.ReadLine();
int result;
bool isValidNumber = Int32.TryParse(userInput, out result);
Console.WriteLine(isValidNumber ? "Hi, You have entered a valid number" : "Entered value is not a vald number, so please type a number!");
Console.ReadLine();
}

Related

C# CMD input validation

I'm trying to make it so that when a number is entered my program will not crash, which this does so far. Then I want it to re ask for an input until the correct charcter type is enetered.
int firstNum;
int Operation = 0;
switch(Operation)
{
case 1:
bool firstNumBool = int.TryParse(Console.ReadLine(), out firstNum);
break;
}
Decompose your solution; extract a method for inputing an integer:
private static int ReadInteger(string title) {
// Keep on asking until correct input is provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value; please, try again.");
}
}
And then use it:
int firstNum;
...
switch(Operation)
{
case 1:
firstNum = ReadInteger("First number");
break;
...

c# Need help trying to put in and run two loops for the same input

I've put in a loop with Try.Parse so that if the user enters a decimal number, the program will ask them to enter another number until they put in a integer and then the program will carry on with the next part.
However what i'm struggling with is putting in another loop that makes it so that the user can only enter a number between 1 and 100, and if they don't there should be an error message that loops until they do enter this. Id like them to run at the same time and i have this one, but i want it to also check whether its in the range and i'm not sure how to do that.
I'm new to programming so I'm not great at this.
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("Please Enter A Valid Integer Value");
Console.WriteLine();
inputcost = Console.ReadLine();
}
}
Your problem here is that the result variable you're looking at is only written once: outside the loop. Consider trying something like the following pseudocode (a do-while loop works exactly the same as a while loop, except it always gets executed once before the condition is checked):
bool validInput;
do
{
// If you set it true to begin with, you can set it false on any unmet conditions
// If it doesn't get set false, you've got a valid input and can exit the loop.
validInput = true;
Read input from user
Check if it's a valid integer, if not print message and validInput = false
Check if it's between 1-100, if not print message and validInput = false;
} while (!validInput);
Then if you want to tackle something more advanced, look at the continue keyword.
Try something like this.
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
if (!(valuecost >=1 && valuecost <=100))
{
Console.Write("Please enter value between 1 and 100.");
}
bool result = int.TryParse(inputcost, out validcost);
if (result == true)
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("Please Enter A Valid Integer Value");
}
}
It would be useful to use a method and do something like:
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = false;
while (!result)
{
result = checkNumber();
}
public static bool checkNumber()
{
if(inputcost < 1 || inputcost > 100)
{
Console.Write("Please Enter a valid value: ");
inputcost = Console.ReadLine();
return false;
}
else
return true;
}
Hope this helps.
string inputcost;
string inputmoney;
int validcost = 0;
int validmoney = 0;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
// only accept integers
while (!int.TryParse(inputcost, out validcost))
{
Console.Write("Please Enter An Integer Value: ");
inputcost = Console.ReadLine();
}
// valid integer input in variable validcost
bool done = false;
while (!done)
{
Console.Write("Enter an integer between 1 and 100: ");
inputmoney = Console.ReadLine();
if (int.TryParse(inputmoney, out validmoney))
{
if (validmoney > 0 && validmoney < 101)
{
done = true;
}
else
{
Console.WriteLine("Invalid input: " + inputmoney);
}
}
else
{
Console.WriteLine("Invalid input: " + inputmoney);
}
}
//validcost is an integer and validmoney is an integer between 1 and 100
Console.WriteLine("validcost: " + validcost + " validmoney: " + validmoney);
Console.ReadKey();

Validate if integer equals string

So im trying to simply check if my variable is entered as a string, I want the if statement to go through and not an unhandled exception...
Here's my code:
Console.Write("Input: ");
int i;
bool success = int.TryParse("", out i);
if (success) {
Console.WriteLine("Enter Integer!");
} else {
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Output: ", i);
}
So what am I doing wrong here? Every time I am entering a string, I'm not getting to the if statement, only a crash!
The problem in your code is that the value passed to TryParse has no connection to the value passed to Convert.ToInt32. You should read the value in, then call TryParse with the same value:
Console.WriteLine("Enter an integer:");
var s = Console.ReadLine();
int i;
if (int.TryParse(s, out i)) {
Console.WriteLine("You entered an integer");
} else {
Console.WriteLine("You did not enter an integer");
}
If you would like to continue reading until the end-user enters a valid int, add a loop, like this:
int i;
do {
Console.WriteLine("Enter an integer:");
var s = Console.ReadLine();
} while (!int.TryParse(s, out i));
I think you should do it this way
Console.Write("Input: ");
int i;
bool success = int.TryParse(Console.ReadLine(), out i); //Getting the input and checking it
if (!success)
{
Console.WriteLine("Enter Integer!");
}
else
{
Console.WriteLine("Output: ", i);
}
In your code you were getting the value in the else statement and if your input cannot be parsed to int, then exception throws.

Cannot implicitly convert type 'string' to 'int'

I'm doing an athlete program and I want to make int salaryCounter = athleteSalary.ToString so when the user enters the salary of the hired professional I can subtract it from the salary of the athlete and print out how much the athlete will have left but when I try to do it the program tells me "Cannot implicitly convert type 'string' to 'int' ". Can someone help me?
{
Console.WriteLine("Please enter the first name of the athlete");
String athleteString = Console.ReadLine();
Console.WriteLine("Please enter the second name of the athlete");
String athleteString2 = Console.ReadLine();
Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", athleteString.ToString(), athleteString2.ToString());
ConsoleKeyInfo KeyInfo = Console.ReadKey();
if (KeyInfo.KeyChar == 'y')
{
Console.WriteLine("Enter the salary of {0} {1}", athleteString.ToString(), athleteString2.ToString());
String athleteSalary = Console.ReadLine();
Console.WriteLine("{0} Is this right?", athleteSalary.ToString());
ConsoleKeyInfo rightathleteSalary = Console.ReadKey();
int salaryCounter = athleteSalary.ToString();
if (rightathleteSalary.KeyChar == 'y')
{
Console.WriteLine("Ok. Lets contiune.");
athleteSalary = Convert.ToString(salaryCounter);
Console.WriteLine(salaryCounter);
int counter = 0;
Console.WriteLine("{0} {1} {2}", athleteString.ToString(), athleteString2.ToString(), salaryCounter.ToString());
Console.WriteLine("Enter the hired help. The max number of people is five. Press any key to start.");
while (counter < 5)
{
Console.ReadKey();
Console.WriteLine("Please enter the first name of the hired help");
String hiredhelpString = Console.ReadLine();
Console.WriteLine("Please enter the Last name of the hired help");
String hiredhelpString2 = Console.ReadLine();
Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
ConsoleKeyInfo KeyInfo5 = Console.ReadKey();
if (KeyInfo5.KeyChar == 'y')
{
Console.WriteLine("Enter the salary of {0} {1}", hiredhelpString.ToString(), hiredhelpString2.ToString());
String hiredhelpSalary = Console.ReadLine();
Console.WriteLine("{0} Is this right?", hiredhelpSalary.ToString());
ConsoleKeyInfo rightSalary = Console.ReadKey();
if (rightSalary.KeyChar == 'y')
{
Console.WriteLine("Ok. Lets contiune.");
}
Console.WriteLine("Record this proffesional? Press y for yess n for no.");
ConsoleKeyInfo RecordKey = Console.ReadKey();
if (RecordKey.KeyChar == 'y')
{
counter = counter + 1;
Console.WriteLine("Number of hired help is {0} They will be paid {1}", counter, hiredhelpSalary);
Console.WriteLine("Press any key to contiune.");
}
else
{
if (RecordKey.KeyChar == 'n')
{
counter = counter - 1;
Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
Console.ReadKey();
Console.WriteLine("Please enter the first name of the hired help");
String hiredhelpString3 = Console.ReadLine();
Console.WriteLine(" Please enter the Last name of the hired help");
String hiredhelpString4 = Console.ReadLine();
Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
ConsoleKeyInfo KeyInfo6 = Console.ReadKey();
if (KeyInfo6.KeyChar == 'y')
{
Console.WriteLine("Record this proffesional? Press y for yess n for no.");
ConsoleKeyInfo RecordKey1 = Console.ReadKey();
if (RecordKey.KeyChar == 'y')
{
counter = counter + 1;
Console.WriteLine("Number of Hired help is {0} press any key to contiune", counter);
Console.WriteLine("Press any key to contiune.");
}
}
}
}
/*******************************************************************************************************/
/************************************************************************************************************************************************************************************************************************************************/
}
else
{
if (KeyInfo5.KeyChar == 'n')
{
Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
Console.ReadKey();
}
}
}
/*************************************************************************************************************************************************************************************************************************************/
Console.WriteLine("");
Console.WriteLine("Athlete's name: {0} {1} Number of Hired help is {2}", athleteString.ToString(), athleteString2.ToString(), counter);
Console.ReadKey();
}
It looks like you're getting confused about variable types. Briefly;
string - stores information character by character. The compiler can't read numbers stored in strings.
int - stores whole numeric values which can be used in calculations.
Your immediate compile problem comes from this line;
int salaryCounter = athleteSalary.ToString();
You're telling the compiler to take altheteSalary which is a string, call the ToString() method which gets the string representation (this is unnecessary when the source is a string) and store the result in an integer.
You need to parse the string to read out the numeric value like this;
int salaryCounter = int.Parse(athleteSalary)
Though, whenever you receive input directly from a user you should code defensively, so instead of int.Parse, use TryParse. That way if your user enters 'Bob' for their salary, you can display an appropriate error;
int salaryCounter;
while(!int.TryParse(athleteSalary, out salaryCounter)
{
Console.Writeline("The salary should be a number, try again");
athleteSalary = Console.ReadLine();
}
Also, you can remove most of the calls to .ToString(), especially where the variable is already a string.
The main issue is that you need to convert your user input to a type other than a string.
There are many ways to do this, but since you are writing a console application that relies heavily on user-entered data, and since some of this data has to be converted to types other than strings, you might consider writing some helper methods that take care of some of the converting and retrying for you.
I've used the following class in several applications with success. Basically, it's just a bunch of methods that accept a string 'prompt' and return a strongly typed result from the user. If the user enters invalid data, then they have to try again until the enter something valid:
class UserInput
{
public static bool GetBool(string prompt)
{
bool result;
List<string> validTrueResponses =
new List<string> {"yes", "y", "true", "t", "affirmative",
"ok", "okay", "yea", "yeah", "yep"};
List<string> validFalseResponses =
new List<string> {"no", "n", "false", "f", "negative",
"never", "not", "nay", "nix"};
while (true)
{
if (prompt != null) Console.Write(prompt);
var input = Console.ReadLine();
if (validTrueResponses.Any(r =>
r.Equals(input, StringComparison.OrdinalIgnoreCase))) return true;
if (validFalseResponses.Any(r =>
r.Equals(input, StringComparison.OrdinalIgnoreCase))) return false;
if (bool.TryParse(input, out result)) break;
Console.WriteLine("Sorry, I don't understand that response. " +
"Please try again.");
}
return result;
}
public static string GetString(string prompt)
{
if (prompt != null) Console.Write(prompt);
return Console.ReadLine();
}
public static int GetInt(string prompt)
{
int input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not valid. Please try again.");
}
return input;
}
public static decimal GetDecimal(string prompt)
{
decimal input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (decimal.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not valid. Please try again.");
}
return input;
}
}
Then, I would create a simple class to represent a Person, which has simply a first name, last name, and salary (and override the ToString method to display first and last name):
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Salary { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
Now we can reduce some duplicated code by creating methods to get a Person name and salary. This will prompt the user for the information, and then give them a chance to correct it before commiting the data:
private static void GetPersonName(Person person, string typeOfPerson)
{
if (person == null) throw new ArgumentNullException("person");
if (string.IsNullOrWhiteSpace(typeOfPerson)) typeOfPerson = "person";
bool inputIsGood = false;
while (!inputIsGood)
{
person.FirstName = UserInput.GetString(
string.Format("Please enter the first name of the {0}: ", typeOfPerson));
person.LastName = UserInput.GetString(
string.Format("Please enter the last name of the {0}: ", typeOfPerson));
Console.WriteLine("You entered: {0}", person);
inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
}
}
private static void GetPersonSalary(Person person)
{
bool inputIsGood = false;
while (!inputIsGood)
{
person.Salary = UserInput.GetDecimal(
string.Format("Enter the salary of {0}: $", person));
Console.WriteLine("You entered: {0:C}", person.Salary);
inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
}
}
That may seem like a lot of code, but here's how you can use it in your application:
private static void Main()
{
var athlete = new Person();
GetPersonName(athlete, "athlete");
GetPersonSalary(athlete);
Console.WriteLine("Enter the hired help. The max number of people is five. " +
"Press any key to start.");
Console.ReadKey();
List<Person> hiredHelpers = new List<Person>();
while (hiredHelpers.Count <= 5)
{
bool addAnotherHelper =
UserInput.GetBool(
string.Format("There are currently {0} helpers. " +
"Do you want to add another (y/n): ",
hiredHelpers.Count));
if (!addAnotherHelper) break;
Person helper = new Person();
GetPersonName(helper, "helper");
GetPersonSalary(helper);
bool recordHelper = UserInput.GetBool("Do you want to record this " +
"professional (y/n): ");
if (recordHelper)
{
hiredHelpers.Add(helper);
}
}
Console.WriteLine();
Console.WriteLine("Athlete's name: {0}, salary: {1:C}.", athlete, athlete.Salary);
Console.WriteLine("Number of Hired help is: {0}", hiredHelpers.Count);
Console.WriteLine("Hired help details:");
hiredHelpers.ForEach(h =>
Console.WriteLine(" - Name: {0}, Salary: {1:C}", h, h.Salary));
Console.ReadKey();
}

Password/Calculator in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am using Microsoft Visual Studio 2010 and using C# and I am trying to create a program that asks the user for a password and you should have 3 attempts to get it right but I don't know how to add a counter variable or an error message. Can someone help me out?
Also the main part of my program is having the user to choose 2 numbers and having them either subtracted, multiplied, added or divided but my code just automatically does that instead of asking the user. Can anyone help me out with this please?
Here is my code:
static string userName = "";
static string passWord = "";
static float numberOne = 0;
static float numberTwo = 0;
static void Main(string[] args)
{
getpassWord();
validatepassWord();
calculatorIntro();
getData();
calcAddition();
calcSubtraction();
calcDivision();
calcMultiplication();
Console.ReadLine();
}
static void getpassWord()
{
while (passWord == "")
{
Console.Write("Please enter the password > ");
passWord = Console.ReadLine();
}
}
static void validatepassWord()
{
if (passWord == "12345")
{
Console.Write("Please enter a valid password > ");
passWord = Console.ReadLine();
}
}
static void calculatorIntro()
{
Console.Write("Please enter your name > ");
userName = Console.ReadLine();
Console.WriteLine("Hello {0}, Welcome to the Calculator!", userName);
Console.WriteLine("After you have entered the password, you must then enter 2 numbers and decide whether they should be added, multiplied, subtracted or divided");
Console.ReadLine();
}
static void getData()
{
Console.Write("Please enter the first number");
numberOne = float.Parse(Console.ReadLine());
Console.Write("Please enter the second number");
numberTwo = float.Parse(Console.ReadLine());
}
static void calcAddition()
{
Console.Write("{0} + {1} = {2}", numberOne, numberTwo, numberOne + numberTwo);
Console.ReadLine();
}
static void calcSubtraction()
{
Console.Write("{0} - {1} = {2}", numberOne, numberTwo, numberOne - numberTwo);
Console.ReadLine();
}
static void calcDivision()
{
Console.Write("{0} / {1} = {2}", numberOne, numberTwo, numberOne / numberTwo);
Console.ReadLine();
}
static void calcMultiplication()
{
Console.Write("{0} * {1} = {2}", numberOne, numberTwo, numberOne * numberTwo);
Console.ReadLine();
}
For the password validation:
Use a do while loop. The condition to terminate would be if the counter reaches three or if the user gets it right.
example
int counter = 0;
boolean passwordCorrect = false;
do {
Console.Write("Please enter the password > ");
passWord = Console.ReadLine();
//If the password is correct,then it will break the loop
if (passWord == "1234") {
passwordCorrect = true;
}
counter++;
} while (counter < 3 && !passwordCorrect);
You are not even asking the user if they want to subtract, add,etc.For that, ask the user in the main method. Then you will call that method depending on what they inputed.
Example.
int choice;
Console.Write("What operation would you like to perform?\n1. Addition\2. Subtraction");
Console.Write("\n3. Multiplication\n4. Division");
choice = Console.ReadLine();
switch (choice)
{
case 1:
calcAddition();
break;
case 2:
calcSubtraction();
break;
case 3:
calcMultiplication();
break;
case 4:
calcDivision();
break;
default:
Console.Writeline("No operation chosen");
break;
}

Categories

Resources