Restarting a program after error in catch statement - c#

I'm trying to restart my program after I catch an error using the catch() function, but I also want it to display the error, stop the rest of the program from running, and restart the program.
This is just a shortened version of my code which I have used as an example.
using System;
namespace Calculator
{
internal class Program
{
private static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}
When it says
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
The break; makes it so the rest of the code stops, and it displays the error. That is good, but the program also ends after that, what I want, is that the program repeats after error. Is there any way that this could happen, but it allows 1) the Console.WriteLine("Please enter a number");, 2) the program to not run the rest of the code (The part where we are asked for a second value), and 3) the program to restart for the beginning. Please let me know if that didn't make sense, as it was a hard to explain. :)

It is very simple you do not need the "break" keyword because "break" terminates the loop execution to continue execution on exception use "continue" keyword without quotes the working fiddle is here
and your code after replacing "break" with "continue" is following
using System;
namespace Calculator
{
public class Program
{
public static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}

Related

I dont press enter but ReadLine() says I did (accidently made it that you cant answer the old one so repost)

Fixed, but now it automatically presses enter when it gets to the Main(); thing and I can't actually input anything in time. Anyone know what's wrong?
using System;
using System.Linq;
namespace Bruh
{
class Program
{
static void Main()
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.WriteLine("Input a whole number");
string poggers = Console.ReadLine();
if (int.TryParse(poggers, out pog))
{
pog = int.Parse(poggers);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
Console.WriteLine("Input a number higher than the previous");
string poggers2 = Console.ReadLine();
if (int.TryParse(poggers2, out pog2))
{
pog2 = int.Parse(poggers2);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.Read();
Console.WriteLine("Would you like to try again? Y/N");
ConsoleKeyInfo answer = Console.ReadKey();
if (answer.KeyChar == 'y' || answer.KeyChar == 'Y')
{
Console.WriteLine("\n");
Main();
}
else if (answer.KeyChar == 'n' || answer.KeyChar == 'N')
{
System.Environment.Exit(1);
}
else
{
Console.WriteLine("ERROR: Y/N not any other character");
Console.Read();
System.Environment.Exit(1);
}
}
}
}
I've reworked your code into something that is more C#-like :-) - find this below.
Highlights:
You use int.TryParse() correctly, but do the conversion again
inside the true code block, using int.Parse().
No need to call System.Environment.Exit(1); to terminate the program, just let it end.
The call main() is actually a recursive call - where a method (function) calls it self. Usable sometimes, but i often leads to a StackOverflow exception. In this case, you get some strange behaviour...
using System;
namespace Bruh2
{
class Program
{
static void Main()
{
bool tryAgain = true;
while (tryAgain)
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.Write("Input a whole number: ");
string poggers = Console.ReadLine();
while (!int.TryParse(poggers, out pog))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers = Console.ReadLine();
}
Console.Write("Input a number higher than the previous: ");
string poggers2 = Console.ReadLine();
while (!int.TryParse(poggers2, out pog2))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers2 = Console.ReadLine();
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.WriteLine();
Console.WriteLine("Would you like to try again? Y/N");
//ConsoleKeyInfo answer = Console.ReadKey();
string answer = Console.ReadKey().KeyChar.ToString().ToLower();
while (answer!="y" && answer!="n")
{
Console.WriteLine("ERROR: Y/N not any other character");
answer = Console.ReadKey().ToString().ToLower();
}
if (answer == "n")
{
tryAgain = false; // terminate the loop (and thereby the program)
}
}
}
}
}

How can I make my C# calculator run as intended

I have a C# calculator I'm trying to get to run however I keep running into problems, particularly with my last function and currently get stuck in an infinite validation loop, how can I make this work as intended which is to take two numbers and based on user input get the answer for their equation.
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello User what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Please enter in a number");
Console.ReadLine();
Console.WriteLine("Please enter a Math Operator: +, -, *, / ");
string beta = IsValidSymbol();
string equation = Console.ReadLine();
string useint1 = Console.ReadLine();
string useint2 = Console.ReadLine();
Console.WriteLine("Please enter another number");
Console.WriteLine(MathSymbols(equation,useint1,useint2));
}
public static double Validation()
{
string numbString = Console.ReadLine();
double numbVerify;
while (!double.TryParse(numbString, out numbVerify))
{
Console.WriteLine("please only enter in numbers and do not leave blank");
numbString = Console.ReadLine();
}
return numbVerify;
}
private static string IsValidSymbol()
{
string mathValidation = Console.ReadLine();
while ((String.IsNullOrEmpty(mathValidation)))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter a Math Operator: +, -, *, / ");
mathValidation = Console.ReadLine();
}
return mathValidation;
}
private static double MathSymbols(string e, string useint1,string useint2)
{
useint1 = Console.ReadLine();
useint2 = Console.ReadLine();
double result;
double userinput1;
double userinput2;
while (!double.TryParse(useint1, out userinput1))
{
Console.WriteLine("please type in a number");
useint1 = Console.ReadLine();
}
while (!double.TryParse(useint2, out userinput2))
{
Console.WriteLine("please type in a number");
useint1 = Console.ReadLine();
}
if (e == "+")
{
result = userinput1 + userinput2;
}
else if (e == "-")
{
result = userinput1 - userinput2;
}
else if (e == "*")
{
result = (userinput1 * userinput2);
}
else if (e == "/")
{
result = (userinput1 / userinput2);
}
result = 0;
return result;
}
}
}
In many places you had an unnecessary call to Console.ReadLine and overriding variables. Also you didn't use your method Validation (think about renaming it to GetValidNumber).
I corrected your code to work for valid input. You still need additional validations and refactoring in your code, good luck!
using System;
namespace CalculatorExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello User what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Please enter in a number");
double useint1 = Validation();
Console.WriteLine("Please enter a Math Operator: +, -, *, / ");
string equation = IsValidSymbol();
Console.WriteLine($"You equation symbol: {equation}");
Console.WriteLine("Please enter another number");
double useint2 = Validation();
double result = MathSymbols(equation, useint1, useint2);
Console.WriteLine($"Result: {result}");
Console.ReadKey();
}
public static double Validation()
{
string numbString = Console.ReadLine();
double numbVerify;
while (!double.TryParse(numbString, out numbVerify))
{
Console.WriteLine("please only enter in numbers and do not leave blank");
numbString = Console.ReadLine();
}
return numbVerify;
}
private static string IsValidSymbol()
{
string mathValidation = Console.ReadLine();
while ((String.IsNullOrEmpty(mathValidation)))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter a Math Operator: +, -, *, / ");
mathValidation = Console.ReadLine();
}
return mathValidation;
}
private static double MathSymbols(string equation, double useint1, double useint2)
{
if (equation == "+")
return useint1 + useint2;
if (equation == "-")
return useint1 - useint2;
if (equation == "*")
return useint1 * useint2;
if (equation == "/")
return useint1 / useint2;
throw new InvalidOperationException($"Unrecognized equation symbol: {equation}");
}
}
}

C# re-enter value after wrong input instead of restarting the program

so I am trying to make a multiplication table with c#, and I want that when user give a wrong input in code it should not start the program from start but just ask to re-enter that value. when I run this code and put wrong input. it will ask to display the multiplication table again. but I want that if I give wrong input at "start value" then it will only ask for re-entering the start value but not the whole input
public void Multi()
{
Console.Write("\n\n");
bool tryAgain = true;
while (tryAgain)
{
try
{
Console.Write("Display the multiplication table:\n ");
int t = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine(" Start value ");
Console.WriteLine("\n");
Console.WriteLine(" End value \n");
int end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
SwapNum(ref start, ref end);
Console.Write("\n");
Console.WriteLine("Display the table\n");
int i = start;
do
{
Console.WriteLine(t + " * " + i + " = " + t * i);
//Console.WriteLine("{0} * {1} = {2}", t, i, t*i);
i++;
} while (i <= end);
}
catch (Exception ex)
{
Console.WriteLine("Please Enter the inter number ");
}
}
}
static void SwapNum(ref int x, ref int y)
{
if (x >= y)
{
int temp = x;
x = y;
y = temp;
}
}
Change Parse into TryParse; let's extract a method for this
private static int ReadInt(string prompt) {
while (true) {
Console.WriteLine(prompt);
int result;
if (int.TryParse(Console.ReadLine(), out result))
return result;
Console.WriteLine("Sorry, it's not a correct integer value, please try again.");
}
}
...
public void Multi() {
Console.Write("Display the multiplication table:\n ");
// Now we keep asking user until the correct value entered
int t = ReadInt("Start value");
...
}

C# converting strings to int's

I'm new to c# and am trying to make a simple calculator.
It works fine until it goes back to the start to take a new number.
When taking the new number it says it cant convert the user input to a integer.
using System;
namespace simpleCalculator
{
class MainClass
{
public static void Main(string[] args)
{
start:
Console.Clear();
Console.WriteLine("Enter first number");
int x = Convert.ToConsole.ReadLine();
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Devide");
string o = Console.ReadLine();
if (o == "1")
{
Console.WriteLine("Enter second number\n");
int y = Convert.ToInt32(Console.ReadLine());
add(temp, y);
goto start;
Console.Clear();
goto start;
}
}
public static void add(int num01, int num02)
{
Console.Clear();
Console.WriteLine((num01 + num02) + "\nPress enter to contiue.");
Console.Read();
}
}
}
Use TryParse so if the parsing fails, you will not get an exception.
var enteredValue = Console.ReadLine();
var parsedValue;
if (!int.TryParse(enteredValue, out parsedValue))
{
// parse failed do whatever you want
}
Do that for both entries and if both of them pass, then call your add method.
You're looking for int.Parse(). Be careful to validate your input. You should probably create an escape condition.
Edited to show an alternative solution
Edited to be more explicit on how to handle some input
class Program
{
public static void Main(string[] args)
{
string input = String.Empty;
int x = 0, y = 0;
while (true)
{
try
{
Console.WriteLine("Enter first number");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Divide");
input = Console.ReadLine();
Console.WriteLine("Please enter a second number");
y = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
continue;
}
switch (input)
{
case "1":
Console.WriteLine($"{x} + {y} = " + add(x, y));
break;
case "2":
//TODO implement multiply case
break;
case "3":
//TODO implement divide case
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
}
public static int add(int x, int y) => x + y;
}
Try this:
int numbers = Convert.ToInt32("1234");

How to reloop the game and ask something

I made a program that calculates the temperature in different ways.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercise_7
{
class Program
{
static void Main(string[] args)
{
showBegin();
decide();
secondPlay();
showEnd();
}
// Decide code
static void decide() {
int choice;
string input;
input = Console.ReadLine();
int.TryParse(input, out choice);
if (choice == 1)
{
Console.WriteLine("");
celciusSystem();
}
else if (choice == 2)
{
Console.WriteLine("");
farenheitSystem();
}
else if (choice == 3)
{
Console.WriteLine("");
kelvinSystem();
}
else {
Console.WriteLine("");
Console.WriteLine("Make sure u write a number between 1 and 3! No text!");
Console.WriteLine("");
showBegin();
decide();
}
}
static void secondPlay()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
}
// Begin code
static void showBegin()
{
Console.WriteLine("Welcom at the temperature calculator, pick the mode u prefer!");
Console.WriteLine("Press 1 for Celcius mode");
Console.WriteLine("Press 2 for Fahrenheit mode");
Console.WriteLine("Press 3 for Kelvin mode");
Console.WriteLine("Press the correct number and then hit the enter button!");
Console.WriteLine("");
}
// Temperature Calculators
static void celciusSystem()
{
Console.WriteLine("This is the Celsius calculator");
Console.Write("Enter the amount of celsius: ");
int celsius = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", celsius + 273);
Console.WriteLine("The temperature in Fahrenheit = {0}", celsius * 18 / 10 + 32);
}
static void farenheitSystem()
{
Console.WriteLine("This is the Fahrenheit calculator");
Console.Write("Enter the amount of Fahrenheit: ");
int Fahrenheit = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", (Fahrenheit + 459.67) / 1.8);
Console.WriteLine("The temperature in Celsius = {0}", (Fahrenheit - 32) / 1.8);
}
static void kelvinSystem()
{
Console.WriteLine("This is the Kelvin calculator");
Console.Write("Enter the amount of Kelvin: ");
int Kelvin = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Fahrenheit = {0}", Kelvin * 1.8 - 459.67);
Console.WriteLine("The temperature in Celsius = {0}", Kelvin - 273.15);
}
// End code
static void showEnd()
{
Console.WriteLine("");
Console.WriteLine("We hoped u enjoyed our application!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
So now my question, I made a class called second play. Within that class i tried to make a kind a statement that would ask the user if he or she wanted to "play" again. So if they write 1 he should loop the game again.
I have tried it with this
if (choice2 == 1)
{
while (choice2 == 1) {
Console.WriteLine("");
showBegin();
decide();
}
}
else {
Console.WriteLine("");
Console.WriteLine("Cheers!!");
}
}
then he actually worked but not the way I wanted to because if the user writes 1 it will loop the first thing all over again. So the user can't quit the game any more.
I want the application to ask after every trail if he or she wants to play again by typing 1 or 2.
You already know how to read lines from the console, you also know how to use if to compare booleans, so why don't you just apply this and check if they wrote a 1 or 2?
private bool playAgain()
{
int number = 2; //Invalid option: close game
Int32.TryParse(Console.ReadLine(), out number);
if (number == 1)
{
return true;
}
else if (number == 2)
{
return false;
}
else
{
Console.WriteLine("Unknown option, quitting!");
return false;
}
}
Then you just have to use that function to determine if they want to play again in a do-loop.
static void Main(string[] args)
{
showBegin(); //Show begin sequence
do
{
decide();
secondPlay();
} while(playAgain()); //Play again if they want to
showEnd(); //Show end sequence when they decided not to play
}
Pro tip: use a switch-case statement instead of multiple if-else statements.
You can use a do while loop, which serves you well in cases like yours, when you want to execute your loop at least once:
do {
Console.WriteLine("");
showBegin();
decide();
//Ask for choice2 here
}
while(choice2 == 1);
Console.WriteLine("");
Console.WriteLine("Cheers!!");
To enter game loop, it is most useful to start with simple while or do-while.
while( conditionToRun )
{
//run the program
if( userWantToExit )
conditionToRun = false;
}
Or
do
{
// run the program
} while ( !userWantToExit )
This code shows the most basic stuff to handle this.
To apply on Your game/program, use:
static void Main(string[] args)
{
bool userWantToEnd = false;
showBegin();
while( !userWantToEnd)
{
decide();
userWantToEnd = IsUserWillingToContinue();
}
showEnd();
}
And adjust the SecondPlay() method into something like IsUserWillingToContinue():
public bool IsUserWillingToContinue()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
return choice2 == 1;
}
Adding more info based on comment of #devRicher - You should split up a bit the code so it work in this way
bool runAgain = true;
Console.WriteLine("Begin info: (Hello this is XY game.)");
while(runAgain)
{
Console.WriteLine("You have 3 options: 1, 2, 3");
PickOptionAndRunTheCode();
bool runAgain = DoYouWantToContinue();
Console.Clear(); // clear the Console screen (next time You will see only options, not the text on first run).
}
I would recommend to get more knowledge about games to go to this page -> http://gameprogrammingpatterns.com/ (and read the book)
Check this pattern: Game Loop

Categories