Odd/even number with the verification of an input - c#

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

Related

Unwanted repeat in method (with user input)

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.

Error detected trying to receive input as an integer in C#

I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = int.Parse(Console.ReadLine());
score += add;
if (input == 18)
{
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
break;
}
else if (input > 25)
{
Console.WriteLine("Error.");
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:
static void Main(string[] args)
{
int number;
string input;
bool guessed = false;
int score = 0;
while (!guessed)
{
Console.Write("Guess A Number Between 1 and 25: ");
input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if(number>=1 && number<=25)
{
score++;
if (number == 18)
{
guessed = true;
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
else
{
Console.WriteLine("Number must be between 1 and 25!");
}
}
else
{
Console.WriteLine("That's not a number!");
}
Console.WriteLine();
}
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}

Try/Catch and loop

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();

How to ban users enter strings or negative numbers

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
}

Saving values within if statement C#

I'm a newbie at C# and I'm having some difficulties writing a program that is going to let you save values in a variable, everything is working fine, except I can't save values into my variable. Here's the code:
while (true)
{
//Menu
Console.WriteLine (" \n\tWelcome!");
Console.WriteLine (" \t[1]Store value");
Console.WriteLine (" \t[2]Write message");
Console.WriteLine (" \t[3]Clear the console");
Console.WriteLine (" \t[4]Shut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32 (Console.ReadLine ());
//Users message
string usrMsg = null;
//if statement
if (choice == 1) {
usrMsg += Console.ReadLine ();
} else if (choice == 2) {
Console.WriteLine (usrMsg);
} else if (choice == 3) {
//Shuts down program
break;
} else if (choice == 4) {
//Clear program
Console.Clear ();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
You just move the usrMsg variable out of while block as a global the value will be saved.
//Users message
string usrMsg = null;
while (true)
{
//Menu
Console.WriteLine(" \n\tWelcome!");
Console.WriteLine(" \t[1]Store value");
Console.WriteLine(" \t[2]Write message");
Console.WriteLine(" \t[3]Clear the console");
Console.WriteLine(" \t[4SShut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32(Console.ReadLine());
//if statement
if (choice == 1)
{
usrMsg += Console.ReadLine();
}
else if (choice == 2)
{
Console.WriteLine(usrMsg);
}
else if (choice == 3)
{
//Shuts down program
break;
}
else if (choice == 4)
{
//Clear program
Console.Clear();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
When this runs it always creates userMsg as null. That means that at best it will 'save' only 1 value when the user chooses '1'. However, this will never get displayed if the user selects '2' as when the user gets to the menu again userMsg will have been set to null again.
My assumption is that you're trying to save the number of times someone has selected '1' and then display that if the user then hits option '2'.
Stick this:
//Users message
string usrMsg = null;
outside of the 'while' loop.

Categories

Resources