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;
...
Related
I'm making a basic calculator and I'm wondering how I would go on to make the user choose if he/she wants to display the full result or only the result with 2 decimals. For example, if user puts in first number 4.213 and second number 4.6321, method "+" then the console asks "Do you wish to display the entire result or round it to 2 decimals" at which the user can type in "Yes" or "No".
I'm not looking for the program to round up the decimals, just display 2 decimals or the entire number.
I'm guessing if and else statement would be the way to go here.
Code:
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
private static int runda;
static void Main(string[] args)
{
List<double> Numbers = new List<double>();
string Method = "";
while (true)
{
loop:
try
{
Numbers.Add(ConvStr(TakeUserInput("First Number:")));
}
catch
{
Console.Clear();
Console.WriteLine("Error, try again.");
Console.ReadLine();
goto loop;
}
Console.Clear();
looop:
try
{
Numbers.Add(ConvStr(TakeUserInput("Second Number:")));
}
catch
{
Console.Clear();
Console.WriteLine("Error, try again.");
Console.ReadLine();
goto looop;
}
Console.Clear();
do
{
Method = TakeUserInput("Choose method: ");
Console.Clear();
Console.WriteLine("Error (Endast Addition (+) Subtraktion (-) Multiplikation (*) samt division (/)");
}
while (!CheckMethod(Method));
Console.Clear();
**HERE IS WHERE I WOULD LIKE USER TO CHOOSE IF DISPLAY ENTIRE NUMBER OR ONLY 2 DECIMALS**
Console.WriteLine("Result:");
Console.WriteLine(Calc(Numbers, Method));
Console.WriteLine("If you wish to keep using this calculator press Enter.");
Console.ReadLine();
Numbers.Clear();
}
}
private static string TakeUserInput(string DisplayText)
{
Console.Write(DisplayText);
return Console.ReadLine();
}
private static bool CheckMethod(string method)
{
switch(method)
{
case "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
return false;
}
return true;
}
private static double Calc(List<double> input, string method)
{
double Answer = 0;
switch (method)
{
case "+":
Answer = input[0] + input[1];
break;
case "-":
Answer = input[0] - input[1];
break;
case "*":
Answer = input[0] * input[1];
break;
case "/":
Answer = input[0] / input[1];
break;
}
return Answer;
}
private static double ConvStr(string input)
{
return Convert.ToDouble(input = input.Replace(".", ","));
}
}
}
Might be wrong but couldn’t you
1). Turn the integer(result) into a string
2). Use the .indexOf(“”) function on the string to get the location of the period
3). check the index+3 to be in range of the result in order to not give any errors (3 to skip the period as well)
4). Use the .remove(index) function to remove all other numbers at the new index
5). Use Convert.toInt32(string) to get its value back
Also there is a “Data.” something function which enables you to calculate the result of a string representation of the expression if that is of any help
I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}
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();
}
back: Console.Write("The first number= ");
int x = int.Parse(Console.ReadLine());
if (x== string ) { goto back;} // here my proplem
How can I model this: Meaning if x input string goto back
Use a loop with int.TryParse that checks if the value is number and break from the loop when the Number is entered correctly.
int x;
while(true)
{
Console.Write("The first number= ");
bool success = int.TryParse(Console.ReadLine(), out x);
if (success)
break;
}
Or if you wish to use goto
int x;
back:
Console.Write("The first number= ");
bool success = int.TryParse(Console.ReadLine(), out x);
if (!success)
goto back;
am trying to make a mastermind game using an array of ints where I having the user guess a number sequence between 4-10 instead of colours. My GetAValidNumber is suppose to displays a prompt to the user and
get a number from the user in the minimum/maximum range as specified in
the parameters. If the number entered is outside the minimum/maximum
range, then an error message is suppose to be displayed and
the user is re-prompted for the number but for some reason it isn't validating properly.
Any Guidance would be appreciated
public static int GetAValidNumber(string inputMessage)
{
// declare variables
int validInteger;
bool inputIsValid = false;
int lowValue = 1;
int highValue = 10;
while (!int.TryParse(Console.ReadLine(), out validInteger))
{
Console.WriteLine("Invalid entery - try again.");
Console.Write(inputMessage, lowValue, highValue);
do
{
while (!int.TryParse(Console.ReadLine(), out validInteger))
{
Console.WriteLine("Invalid entery - try again.");
Console.Write(inputMessage);
}
if (validInteger < lowValue || validInteger > highValue)
{
Console.WriteLine("Your number is out of Range: ");
}
else
{
inputIsValid = true;
}
} while (validInteger < lowValue || validInteger > highValue);
}
return validInteger;
}
// This method directs the play of the game
public static void PlayGame()
{
int userNumbers;
int userGuess;
int difficulty;
int randomNumbers;
Console.WriteLine("How Many Numbers Would You Like To Use When Playing(4-10): ");
userNumbers = GetAValidNumber(Console.ReadLine());
Console.WriteLine("Choose a difficulty level (1 -3");
difficulty = GetAValidNumber(Console.ReadLine());
Console.WriteLine("A 5-digit number has been chosen. Each possible digit may be the number 1, 2, 3, or 4");
Console.ReadLine();
Console.WriteLine("Enter Your Guess {0} guesses remaning", GetGameDifficulty(difficulty, randomNumbers = GetRandomNumberCount(difficulty)));
userGuess = GetAValidNumber(Console.ReadLine());
Console.WriteLine("Your Guess was {0}, Your Results are {1}", userGuess, CountHits(userGuess, randomNumbers));
Console.ReadLine();
}
Here's a simplified version of your code:
public static int GetAValidNumber(string inputMessage)
{
int validInteger = 0;
//Range between 4 to 10
int lowValue = 4;
int highValue = 10;
int.TryParse(inputMessage, out validInteger);
while (validInteger < lowValue || validInteger > highValue)
{
Console.WriteLine("Invalid entery - try again.");
inputMessage = Console.ReadLine();
int.TryParse(inputMessage, out validInteger);
}
return validInteger;
}
The issue here is you are having multiple while loops that is not validating your inputs correctly.
Take note that on your other validating number inputs you need different ranges so I would suggest setting the lowValue and highValue as extra parameters on your function:
public static int GetAValidNumber(string inputMessage, int lowValue, int highValue)