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.
Related
Having some problems with my Console Calculator
I want to prohibit user inputing a words instead of numbers.
I wrote this code and its converting words to zero but i want user to type a number instead of words. And if user still typing words program should ask user to type number.
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("----------------------");
Console.WriteLine("------Calculator------");
Console.WriteLine("----------------------");
do
{
double num1 = 0;
double num2 = 0;
double result = 0;
bool result0;
Console.WriteLine("Enter number one: ");
try
{
double.TryParse(Console.ReadLine(), out num1);
if ()
{
Console.WriteLine("Incorrect number!\nType another number:");
num1 = Convert.ToDouble(Console.ReadLine());
}
}
catch (Exception e)
{
}
Console.WriteLine("Enter number two: ");
num2 = Convert.ToDouble(Console.ReadLine());
You have to use double.TryParse() inside a if condition with negation operator.
If you want to force user to show "Incorrect number!\nType another number:" message till the user enters correct integer, use while() loop instead of if() condition.
while (!double.TryParse(Console.ReadLine(), out num1))
Console.WriteLine("Incorrect number!\nType another number:");
Why we should use double.TryParse() inside if condition?
double.TryParse(), parse string value to double and return true if conversion succeeded or not.
In your case, if user enters word instead of number then conversion will fail and use of !(negation) will iterate the loop again.
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.");
}
I have a bit code of console application whose job is to get numbers from the user and add them to the array. But the problem is that I don't know how many numbers the user is going to input. So I decided to add some sort of stop key. For example, if there are enough numbers user can press "N" and continue to another part of code. So my first problem is how to make this code to not give unhandled format exception when any key is pressed.
int[] arrayInt = new int[100];
for (int i = 0; i < arrayInt.Length; i++)
{
arrayInt[i] = int.Parse(Console.ReadLine());
if (arrayInt[i] == Convert.ToChar (ConsoleKey.N))
{
//for example
Console.WriteLine("You pressed n");
}
If you want only a number or a letter, then you should use Console.ReadKey instead of Console.ReadLine.
You can use the following code, to get what you want.
int[] arrayInt = new int[100];
for (int i = 0; i < arrayInt.Length; i++)
{
var input = Console.ReadLine();
if(input.Equals("n")){
//for example
Console.WriteLine("You pressed n");
}else{
if(int.TryParse(input, out arrayInt[i])){
Console.WriteLine("It's a number");
}else{
Console.WriteLine("No number and no n!");
}
}
}
You uses ConsoleKey.N, to check the "n". But with this, the user have to input "N". "n" doesn't work. If you want it not case sensetive, than you can change this line from my code:
if(input.Equals("n")){
to
if(input.ToLower().Equals("n")){
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.
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.
// ...
}