Try/Catch and loop - c#

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

Related

How to ask until the user get specific reply in C#

{
bool stayInLoop = true;
while(stayInLoop)
{
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
}
I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)
You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
switch(exp)
{
case "+":
{
var sum = 0;
for(;;)
{
Console.WriteLine("Enter Yor Number");
var line = Console.ReadLine();
if (line == ";") break;
sum += Convert.ToInt32(line);
}
Console.WriteLine(sum);
break;
}
}
Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.
Use a while loop:
switch(exp)
{
case "+":
int sum = 0;
string input = "";
do
{
Console.WriteLine("Enter your number:");
input = Console.ReadLine();
if (input != ";")
sum += int.Parse(input);
} while (input != ";");
Console.WriteLine("Answer =" + sum);
break;
}
You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
case "+":
int mySum = 0;
string userInput = "";
while(userInput != ";")
{
Console.WriteLine("Enter number to add (';' to end the sum):");
userInput = Console.ReadLine();
if (userInput != ";")
{
// Would be interesting checking if entered really is an integer, for example Int32.TyParse()
mySum = mySum + Convert.ToInt32(userInput);
}
}
Console.WriteLine("Answer =" + mySum.ToString());
break;
}
Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
bool stayInLoop = true;
while(stayInLoop)
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
and when I run this, it run out 'error CS0019' and 'error CS0139'
What you're looking for is a while() loop.
example:
bool stayInLoop = true;
while(stayInLoop) // basically means (stayInLoop == true)
{
var text = Console.ReadLine();
if(text == ';')
{
stayInLoop = false;
break; // break will stop the loop, but you can also change the variable to false to break the loop.
}
}

implementing a play again feature in a random number guess generator

I have been doing some programming exercises in university lately and i came across one that wanted the user to guess between the numbers 1 and 100. They also want it to have the ability to let the user play again. When first ran the program is fine but when i say 'y' to play again it generates the same number i previously guessed:
I found some solutions however there was so much spaghetti code i couldn't read it on websites. is there any way to save a few lines of code.
here is my source:
int guess = 0;
Random r1 = new Random();
int answer = r1.Next(1, 100);
bool finished = false;
while (!finished)
{
Console.WriteLine("please guess a number between 1 - 100");
guess = int.Parse(Console.ReadLine());
if (guess < answer)
{
Console.WriteLine("your answer is too low please try again!");
}
else if (guess > answer)
{
Console.WriteLine("your answer is too high please try again!");
}
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if (playAgain == "n")
{
finished = true;
}
}//end of nested else
}//end of while
The reason why the same number is being given every time to guess is that you do not generate it if the user wants to continue the game, but instead you use what was already declared.
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if (playAgain == "n")
{
finished = true;
}
answer = r1.Next(1,100);
}//end of nested else
If you want to get rid of some lines, then you can simply declare some variable inside of the loop.
Random r1 = new Random();
int answer = r1.Next(1, 100);
while (true)
{
Console.WriteLine("please guess a number between 1 - 100");
guess = int.Parse(Console.ReadLine());
if (guess < answer)
{
Console.WriteLine("your answer is too low please try again!");
}
else if (guess > answer)
{
Console.WriteLine("your answer is too high please try again!");
}
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
if (Console.ReadLine() == "n")
{
break; // stop the loop
}
}//end of nested else
}//end of while
Because before restarting the guess, the field "answer" is always the previously generated random value "54". Therefore, if the user enters "y", you can add a statement to reset the value of "answer".
// code omitted
// ...
// reset answer
if(playAgain == "y")
{
answer = r1.Next(1, 100);
}
if (playAgain == "n")
{
finished = true;
}

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

How to allow user to quit console app at any time?

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
}

Odd/even number with the verification of an input

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

Categories

Resources