I tried to do a function this way, but once it shows the MessageBox, it then jumps out to the GUI and says the wrong message with the last sentence.
if (!(double.TryParse(Waisttb.Text, out waist) && double.TryParse(Heighttb.Text, out height))) {
MessageBox.Show("Please enter a valid number!");
}
//no negative numbers
if (waist < 0 || height < 0) {
MessageBox.Show("Please enter a valid number!");
}
else {
//change to doubles
waist = double.Parse(Waisttb.Text);
}
You have to reorder your logic. Also, there is no use in re-parsing the already parsed values.
if (!(double.TryParse(Waisttb.Text, out waist) && double.TryParse(Heighttb.Text, out height)))
{
// input is not a valid number
MessageBox.Show("Please enter a vailable number!");
}
else if (waist < 0 || height < 0)
{
// numbers are valid, but negative
MessageBox.Show("Please enter a vailable number!");
}
else
{
// numbers are valid and positive. use them here
}
Related
I have a fairly specific question on this otherwise functional piece of code. The problem is that whenever I run it, there is always a blank spot after the value, so the user has to enter their input twice. So the output would say...
pic related
public string GetPayType()
{
Console.WriteLine("Please enter 1 if your pay type is a weekly hourly wage and 2 if your pay type is a monthly salary:");
if (Console.ReadLine() == "1")
{
payType = Convert.ToString(Console.ReadLine());
return payType;
}
else if (Console.ReadLine() == "2")
{
payType = Convert.ToString(Console.ReadLine());
return payType;
}
else
{
Console.WriteLine("Error! You may only enter a 1 or a 2!");
}
return payType;
}
By doing the line below again after comparing the first input, you are basically prompting for another input to return.
payType = Convert.ToString(Console.ReadLine());
return payType;
Try:
public string GetPayType()
{
Console.WriteLine("Please enter 1 if your pay type is a weekly hourly wage and 2 if your pay type is a monthly salary:");
payType = Console.Readline();
if (payType == "1" || payType == "2")
{
return payType;
}
else
{
Console.WriteLine("Error! You may only enter a 1 or a 2!");
}
return null;
}
You might as well want to add a loop for the user if they entered an invalid input, I'll leave that to you for your own research.
I came across this situation however I don't know how do I handle this exception when the user enters a number outside of the index of the string or any other datatype. In that condition I want the program to display the exception and go back to the first if statement. The code must be as basic as possible as I have just started learning programming. I know the use of 'Try Catch' (or so I think) but I can't determine how to use it here.
choice = int.Parse(Console.ReadLine());
if (arr[choice] != 'X' && arr[choice] != 'O')
{
if (player % 2 == 0)
{
arr[choice] = 'O';
player++;
}
else
{
arr[choice] = 'X';
player++;
}
}
else
{
Console.WriteLine("Sorry the row {0} is already marked with {1}", choice,arr[choice]);
Console.WriteLine("\n");
}
You can do it like this:
int choice;
bool isValidChoice = int.TryParse(Console.ReadLine(), out choice) && choice >= 0 && choice < arr.Length;
if (isValidChoice && arr[choice] != 'X' && arr[choice] != 'O') {
if (player % 2 == 0) {
arr[choice] = 'O';
player++;
} else {
arr[choice] = 'X';
player++;
}
} else if (!isValidChoice) {
Console.WriteLine("Sorry you have not entered a valid in-range integer");
} else {
Console.WriteLine("Sorry the row {0} is already marked with {1}", choice, arr[choice]);
Console.WriteLine("\n");
}
Some explanations:
int.TryParse, is effectively the equivalent of
int choice;
bool isValid = false;
try {
choice = int.Parse(Console.ReadLine());
isValid = true;
} catch {}
&& will only be evaluated only when the previous statement is correct. So in
choice >= 0 && choice < arr.Length the choice < arr.Length will only be checked if the choice >= 0 is correct
If you want to retry as long as the input is invalid. Try using the while(!isValidChoice) loop. I will not tell you how, as I think it will be a good learning experience.
Can someone help me make the option to quit the app at anytime work in this code? Also, I was wondering why I have to hit enter twice for the message "That is not an integer" when the user enters a string instead of a number?
using System;
using System.Threading;
namespace farino_HighLow
{
public class Game
{
// TAKES AND TRACKS USER INPUT
public void PlayGame()
{
// CREATES VARIABLE FOR INPUT FROM THE USER (IF THEY MAKE AN INVALID GUESS OR WANT TO EXIT),
// THE RANDOM VALUE GENERATED, THE USERS GUESS, AND A COUNTER FOR HOW MANY GUESSES THE USER TAKES
Random random = new Random();
int returnValue = random.Next(1, 100);
string input;
string line;
int guess = 0;
int count = 0;
Console.Beep(1000, 2000);
// INSTRUCTS USER WHAT TO DO
Console.WriteLine("Guess a number between 1-100");
Console.WriteLine("Hit Q at any time to exit the game");
do
{
input = Console.ReadLine();
try
{
guess = Convert.ToInt32(input);
}
catch
{
if (input == "Q")
{
break;
}
}
line = Console.ReadLine();
if (!int.TryParse(line, out guess))
Console.WriteLine("Not an integer!");
// MAKES SURE USER ENTERS A NUMBER WITHIN THE PARAMETERS OF THE GAME
// COUNTS THE USER GUESSES
// TELLS USER IF THEIR GUESS WAS RIGHT OR WRONG AND DIRECTS THEM TOWARDS A BETTER GUESS
if (guess >= 1 && guess <= 100)
{
if (guess > returnValue)
{
Console.Beep(100,2000);
Console.WriteLine("Guess Again! Your guess is too HIGH");
count += 1;
}
if (guess < returnValue)
{
Console.Beep(300,2000);
Console.WriteLine("Guess Again! Your guess is too LOW");
count += 1;
}
if (guess == returnValue)
{
Console.Beep(50,2000);
Console.Beep(60,2000);
Console.Beep(70,2000);
Console.WriteLine("You got it RIGHT!!!!!!");
count += 1;
Console.WriteLine("It took you" + count + "guesses to win the game.");
}
if (guess < 1)
{
Console.WriteLine("That is not a valid entry");
}
if (guess > 100)
{
Console.WriteLine("That is not a valid entry");
}
}
} while (guess != returnValue);
Thread.Sleep(5000);
Console.Clear();
}
}
}
Try This code
using System;
using System.Threading;
namespace farino_HighLow
{
public class Game
{
// TAKES AND TRACKS USER INPUT
public void PlayGame()
{
// CREATES VARIABLE FOR INPUT FROM THE USER (IF THEY MAKE AN INVALID GUESS OR WANT TO EXIT),
// THE RANDOM VALUE GENERATED, THE USERS GUESS, AND A COUNTER FOR HOW MANY GUESSES THE USER TAKES
Random random = new Random();
int returnValue = random.Next(1, 100);
string input;
string line;
int guess = 0;
int count = 0;
Console.Beep(1000, 2000);
// INSTRUCTS USER WHAT TO DO
Console.WriteLine("Guess a number between 1-100");
Console.WriteLine("Hit Q at any time to exit the game");
do
{
input = Console.ReadLine();
try
{
guess = Convert.ToInt32(input);
}
catch
{
if (input == "Q")
{
//after press Q exit from application
return;
}
}
line = Console.ReadLine();
if (!int.TryParse(line, out guess))
Console.WriteLine("Not an integer!");
// MAKES SURE USER ENTERS A NUMBER WITHIN THE PARAMETERS OF THE GAME
// COUNTS THE USER GUESSES
// TELLS USER IF THEIR GUESS WAS RIGHT OR WRONG AND DIRECTS THEM TOWARDS A BETTER GUESS
if (guess >= 1 && guess <= 100)
{
if (guess > returnValue)
{
Console.Beep(100, 2000);
Console.WriteLine("Guess Again! Your guess is too HIGH");
count += 1;
}
if (guess < returnValue)
{
Console.Beep(300, 2000);
Console.WriteLine("Guess Again! Your guess is too LOW");
count += 1;
}
if (guess == returnValue)
{
Console.Beep(50, 2000);
Console.Beep(60, 2000);
Console.Beep(70, 2000);
Console.WriteLine("You got it RIGHT!!!!!!");
count += 1;
Console.WriteLine("It took you" + count + "guesses to win the game.");
}
if (guess < 1)
{
Console.WriteLine("That is not a valid entry");
}
if (guess > 100)
{
Console.WriteLine("That is not a valid entry");
}
}
} while (guess != returnValue);
Thread.Sleep(5000);
Console.Clear();
}
}
}
Simply use either: Environment.Exit(0); or Application.Exit();
if(condition is true)
{
Environment.Exit(0);
}
else
{
//continue
}
I'm trying to make a simple odd/even number program, but I want to compare did user entered number. When I enter any symbol which is not a number I get second exception, but when I just press enter ie. not giving any value, I still get a second except except the first one, which I'm trying to get when I don't give any value. My question is how to get a first exception text when I just press enter, since right now I only get second one, whatever I enter.
Console.WriteLine("Enter a number: ");
try
{
var number = int.Parse(Console.ReadLine());
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");
else
Console.WriteLine($"Entered number {number} is odd.");
}
catch (ArgumentNullException)
{
Console.WriteLine("You need to enter some value.");
}
catch (Exception)
{
Console.WriteLine("You need to enter a number.");
}
You should catch FormatException in case you just press enter as string.Empty is being passed to int.Parse. ArgumentNullException is being thrown only if the input value which was passed to int.Parse is null. Here is example how you can do this and write different messages depending on the inputed value:
Console.WriteLine("Enter a number: ");
string input = Console.ReadLine();
try
{
var number = int.Parse(input);
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");
else
Console.WriteLine($"Entered number {number} is odd.");
}
catch (FormatException exc)
{
if(string.IsNullOrEmpty(input))
{
Console.WriteLine("You need to enter some value.");
}
else
{
Console.WriteLine("You need to enter a number.");
}
}
catch (Exception exc)
{
Console.WriteLine("You need to enter a number.");
}
Try this:
var str = Console.ReadLine();
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("You need to enter some value.");
}
else
{
int number;
if (!int.TryParse(str, out number))
{
Console.WriteLine("You need to enter a number.");
}
else
{
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");
else
Console.WriteLine($"Entered number {number} is odd.");
}
}
If you don't enter any value, the value is not null but ""(empty string), that's why it's not an ArgumentNullException
Do how George Alexandria suggested
string s = Console.ReadLine();
if(s == "")
{ Console.WriteLine("You need
to enter some value."); }
1)After try and catch i want to loop it again to give new number("Console.ReadLine("Give correct number"))because user does not entered string convertable to double
2Second problem is, when user give wrong number i would like to loop again to enter new number. This version of program give message to small or to big number and exit
corrected
double number=10,11;
Console.WriteLine("Give a number");
string w=Console.ReadLine();
try
{
double d = Convert.ToDouble(w);
}
catch(FormatException)
{
Console.WriteLine("it is not a number");
}
double dd=Convert.ToDouble(w);
if (dd == number)
{
Console.WriteLine("Yes, it is!");
}
else if (number<dd)
{
Console.WriteLine("to big number");
}
else if(number>dd)
{
Console.WriteLine("to small number");
}
Console.ReadLine();
First, use a do..while(condition) to keep asking until the user enters a valid number. Second, use TryParse to check if the value is valid. This is better than exception handling and converting it twice. Not sure why you are using doubles, but ints might be more appropriate.
bool valid = false;
do
{
bool newValidState;
Console.WriteLine("Give a number");
string w = Console.ReadLine();
double d;
if (!double.TryParse(w, out d))
{
Console.WriteLine("it is not a number");
newValidState = false;
}
else if (d == number)
{
Console.WriteLine("Yes, it is!");
newValidState = true;
}
else if (wyliczona < wybor) // these conditions seem unrelated to `d`
// are they okay?
{
Console.WriteLine("to big number");
newValidState = false;
}
else if(wyliczona > wybor)
{
Console.WriteLine("to small number");
newValidState = false;
}
else
{
Console.WriteLine("unknown condition. needs work.");
newValidState = false;
}
valid = newValidState;
}
while (!valid);
Note the use of newValidState, which will make sure you always assign a new value to valid. This helps to prevent endless loops due to never setting a value. The code will not compile unless every branch sets newValidState to a value.
Try this one:
var number =3;
do{
Console.WriteLine("Give a number");
string w=Console.ReadLine();
try
{
double d = Convert.ToDouble(w);
}
catch(FormatException)
{
Console.WriteLine("it is not a number");
continue; // not a number starting new iteration of the loop
}
double dd=Convert.ToDouble(w);
if (dd == number)
{
Console.WriteLine("Yes, it is!");
break; // The number guessed exiting loop
}
else if (dd>number)
{
Console.WriteLine("to big number");
}
else if(dd<number)
{
Console.WriteLine("to small number");
}
}
while (true);
Console.ReadLine();