How can I make my C# calculator run as intended - c#

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

Related

want my output to have a error message when the user tries to enter decimal and an error message if the user tries to enter any string other than exit

using System;
namespace LabExer2_CMS
{
class Program
{
double fnum;
double snum;
double answer;
string str;
static void Main(string[] args)
{
double fnum;
double snum;
double answer;
string str;
Console.WriteLine("CALCULATOR");
Console.WriteLine(" ");
Console.WriteLine("First Number: ");
fnum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Select an operator: (+, -, * )");
str = Console.ReadLine();
Console.WriteLine("Second Number: ");
snum = Convert.ToInt32(Console.ReadLine());
if (str == "+")
{
answer = fnum + snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "-")
{
answer = fnum - snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "*")
{
answer = fnum * snum;
Console.WriteLine("The answer is: " + answer);
}
Console.Write("PRESS ENTER TO EXIT");
Console.ReadKey();
}
}
}
The first answer is better, but if it's hard to understand, you may try this one.
You may wrap the lines with Console.ReadLine() in try {} catch {} operator, then you need to initialize fnum and snum when you declare them. And you should check the operator as well.
static void Main(string[] args)
{
double fnum = 0;
double snum = 0;
double answer;
string str;
Console.WriteLine("CALCULATOR");
Console.WriteLine(" ");
Console.WriteLine("First Number: ");
try
{
fnum = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Error!");
return;
}
Console.WriteLine("Select an operator: (+, -, * )");
str = Console.ReadLine();
if (str != "+" && str != "-" && str != "*")
{
Console.WriteLine("Wrong operator!");
return;
}
Console.WriteLine("Second Number: ");
try
{
snum = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Error!");
return;
}
if (str == "+")
{
answer = fnum + snum;
Console.WriteLine("The answer is: " + answer);
}
if (str == "-")
{
answer = fnum - snum;
Console.WriteLine("The answer is: " + answer);
}
if (str == "*")
{
answer = fnum * snum;
Console.WriteLine("The answer is: " + answer);
}
Console.Write("PRESS ENTER TO EXIT");
Console.ReadKey();
}
if it helps you
using System;
namespace LabExer2_CMS
{
class Program
{
double fnum;
double snum;
double answer;
string str;
/// <summary>
/// Used instead of the original:
///
/// Console.WriteLine("First Number: ");
/// fnum = Convert.ToInt32(Console.ReadLine());
///
/// resp.
///
/// Console.WriteLine("Second Number: ");
/// snum = Convert.ToInt32(Console.ReadLine());
///
/// </summary>
static double getDouble(string msg) {
double res = 0;
string input = "";
bool isOk = false;
while (!isOk) {
Console.WriteLine(msg);
input = Console.ReadLine();
isOk = double.TryParse(input, out res);
if(!isOk) { Console.WriteLine("Invalid input."); }
}
return res;
}
/// <summary>
/// Used instead of the original:
///
/// Console.WriteLine("Select an operator: (+, -, * )");
/// str = Console.ReadLine();
///
/// </summary>
static string getOperator(string msg1, string[] operators) {
string res = "";
string input = "";
bool isOk = false;
string msg2 = String.Join(",", operators);
string msg = msg1 + "(" + msg2 + ") ";
while (!isOk) {
Console.WriteLine(msg);
input = Console.ReadLine();
isOk = Array.IndexOf(operators, input) >= 0;
if(!isOk) { Console.WriteLine("Invalid input."); }
}
return res;
}
static void Main(string[] args)
{
double fnum;
double snum;
double answer;
string str;
Console.WriteLine("CALCULATOR");
Console.WriteLine(" ");
fnum = getDouble("First Number: ");
string[] operators = new string [] {"+", "-", "*"};
str = getOperator("Select an operator: ", operators);
snum = getDouble("Second Number: ");
if (str == "+")
{
answer = fnum + snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "-")
{
answer = fnum - snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "*")
{
answer = fnum * snum;
Console.WriteLine("The answer is: " + answer);
}
Console.Write("PRESS ENTER TO EXIT");
Console.ReadKey();
}
}
}

Restarting a program after error in catch statement

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

Return to Start/Top in C # console application

I am trying to go back to start in c# console program, and i am somehow able to do it, but the problem is that i am not able to do it using the Y/N statement. mean if i type the Y (yes) from keyboard then the program start from it's starting (beginning) point if i type N then it will terminate the program.
My Console code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace simple_calculation
{
class Program
{
static void Main(string[] args)
{
bool bktop = true;
string option;
while (bktop)
{
Console.WriteLine("Please enter the values");
int val = int.Parse(Console.ReadLine());
int val1 = int.Parse(Console.ReadLine());
int res = val + val1;
int red = val / val1;
Console.WriteLine("Please enter the operator");
string oper=Console.ReadLine();
if (oper == "+")
{
Console.WriteLine("sum is:" + res);
}
else if (oper == "/")
{
Console.WriteLine("division is:" + red);
}
else
{
Console.WriteLine("do you want to continue? enter Y/N");
option = Console.ReadLine();
if(option=="Y")
{
bktop = false;
}
else
{
bktop = true;
}
}
Console.ReadLine();
}
}
}
}
What I want: i want that when the program reaches to the else condition then there is a text appear in the console "do you want to continue? enter Y/N" if the user enter Y then the program start again and if the user enter N then the program will terminate.
Any help will be appreciated.
class Program
{
static void Main(string[] args)
{
// Change 1
bool bktop = true;
string option;
while (bktop)
{
bktop = true;
Console.WriteLine("Please enter the values");
int val = int.Parse(Console.ReadLine());
int val1 = int.Parse(Console.ReadLine());
int res = val + val1;
int red = val / val1;
Console.WriteLine("Please enter the operator");
string oper = Console.ReadLine();
if (oper == "+")
{
Console.WriteLine("sum is:" + res);
}
else if (oper == "/")
{
Console.WriteLine("division is:" + red);
}
else
{
Console.WriteLine("do you want to continue? enter Y/N");
option = Console.ReadLine();
// Change 2
if (option.ToUpper() != "Y")
{
bktop = false;
}
}
}
}
}

C# Program Validation

I need some help making sure that when the user enters nothing, or not a number, it doesn't crash. I have it down so that it will tell them to enter a number if they don't, but I don't know how to make it go back to the original question and give them a chance to input correctly. Thanks for the help.
Console.WriteLine("How much is rent: ");
string strRent = Console.ReadLine();
double dblRent = 0.0;
if (double.TryParse(strRent, out dblRent))
{
Console.WriteLine("How much is the car payment: ");
string strCarPayment = Console.ReadLine();
double dblCarPayment = Convert.ToDouble(strCarPayment);
}
else
{
Console.WriteLine("Enter a number");
}
Console.WriteLine("How much is student loan payment: ");
string strStudentLoan = Console.ReadLine();
Console.WriteLine("How much is phone bill: ");
string strPhoneBill = Console.ReadLine();
Console.WriteLine("How much is electric bill: ");
string strElectricBill = Console.ReadLine();
Console.WriteLine("Fraction deposited: ");
string strFractionDeposited = Console.ReadLine();
Console.WriteLine("Amount leftover: ");
string strAmountLeft = Console.ReadLine();
double dblStudentLoan = Convert.ToDouble(strStudentLoan);
double dblPhoneBill = Convert.ToDouble(strPhoneBill);
double dblElectricBill = Convert.ToDouble(strElectricBill);
double dblFractionDeposited = Convert.ToDouble(strFractionDeposited);
double dblAmountLeft = Convert.ToDouble(strAmountLeft);
double dblBillSum = dblRent + dblCarPayment + dblStudentLoan + dblPhoneBill + dblElectricBill;
double afterBills = dblAmountLeft / (1 - dblFractionDeposited);
double totalPaycheck = afterBills + dblBillSum;
Console.WriteLine("Total Paycheck: " + totalPaycheck.ToString("C"));
Console.WriteLine("Enter wage $/hr: ");
string strWage = Console.ReadLine();
Console.WriteLine("Enter hours worked overtime: ");
string strHoursOT = Console.ReadLine();
Console.WriteLine("Enter overtime multiplier: ");
string strOTWage = Console.ReadLine();
double dblWage = Convert.ToDouble(strWage);
double dblHoursOT = Convert.ToDouble(strHoursOT);
double dblOTWage = Convert.ToDouble(strOTWage);
double OTPay = (dblWage * dblOTWage) * dblHoursOT;
Console.WriteLine("Overtime Pay: " + OTPay.ToString("C"));
Console.ReadLine();
}
}
}
You need a loop, something like this
Console.WriteLine("How much is rent: ");
string strRent = Console.ReadLine();
double dblRent = 0.0;
while (!double.TryParse(strRent, out dblRent))
{
Console.WriteLine("Enter a number");
strRent = Console.ReadLine();
}
Console.WriteLine("How much is the car payment: ");
string strCarPayment = Console.ReadLine();
double dblCarPayment = Convert.ToDouble(strCarPayment);
Try this
double dblRent = 0.0;
Boolean valid = false;
while (!valid)
{
if (double.TryParse(strRent, out dblRent))
{
Console.WriteLine("How much is the car payment: ");
string strCarPayment = Console.ReadLine();
double dblCarPayment = Convert.ToDouble(strCarPayment);
valid = true;
}
else
{
Console.WriteLine("Enter a number");
}
}​
Since you are reading many doubles, you could create a method encapsulating reading and processing the number
private static double? ReadLineDouble()
{
while(true) {
string s = Console.ReadLine();
if (String.IsNullOrWhitespace(s)) {
return null; // The user wants to abort
}
double d;
if (Double.TryParse(s, out d)) {
return d;
}
Console.WriteLine("Please enter a valid number");
}
}
If the user just hits Enter probably he wants to abort. In this case the method returns null. This is possible, because the return type is a Nullable<double>. The shorthand notation for it is double?.
Now you can read a number like this:
double? rent = ReadLineDouble();
if (double == null) return; // Abort the program.
// Otherwise continue.

How do I prevent crashing due to invalid input in C#?

The program I've written is set to only accept positive integers as input. If the user inputs a letter instead, then it crashes. Negative integers don't cause any problems, though it's not 'valid' in regards to how my program functions.
What I want to do is:
Prevent the program from crashing from invalid input.
Display an error message if the input is invalid
Have the program continue where it left off, without affecting the rest of the program.
Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?
This is in C#
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue;
do
{
Console.WriteLine("Enter Striking Level: ");
string striking = Console.ReadLine();
Console.WriteLine("Enter Grappling Level: ");
string grappling = Console.ReadLine();
Console.WriteLine("Enter Submission Level: ");
string submission = Console.ReadLine();
Console.WriteLine("Enter Durability Level: ");
string durability = Console.ReadLine();
Console.WriteLine("Enter Technical Level: ");
string technical = Console.ReadLine();
Console.WriteLine("Enter Speed Level: ");
string speed = Console.ReadLine();
Console.WriteLine("Enter Hardcore Level: ");
string hardcore = Console.ReadLine();
Console.WriteLine("Enter Charisma Level: ");
string charisma = Console.ReadLine();
int gra = Convert.ToInt32(grappling);
int str = Convert.ToInt32(striking);
int dur = Convert.ToInt32(durability);
int spd = Convert.ToInt32(speed);
int tec = Convert.ToInt32(technical);
int hdc = Convert.ToInt32(hardcore);
int cha = Convert.ToInt32(charisma);
int sub = Convert.ToInt32(submission);
int total = str + gra + sub + dur + tec + spd + cha + hdc;
int overall = total / 8 + 8;
Console.WriteLine("The Overall is " + overall);
Console.WriteLine("Do you wish to continue? y/n? ");
if (Console.ReadLine() == "y")
{
shouldContinue = true;
}
else break;
} while (shouldContinue == true);
}
}
}
int value = 0;
if (!int.TryParse(input, out value))
{
MessageBox.Show("Oops");
} else {
// use the value in the variable "value".
}
static void Main(string[] args)
{
bool validInput = false;
string inputString;
UInt32 validPositiveInteger = 0;
while (!validInput)
{
Console.WriteLine("Please enter a positive 32 bit integer:");
inputString = Console.ReadLine();
if (!UInt32.TryParse(inputString, out validPositiveInteger))
{
Console.WriteLine("Input was not a positive integer.");
}
else if (validPositiveInteger.Equals(0))
{
Console.WriteLine("You cannot enter zero.");
}
else
{
validInput = true;
//Or you could just break
//break;
}
}
Console.WriteLine(String.Format("Positive integer = {0}", validPositiveInteger));
}
Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue = true;
while (shouldContinue)
{
int strikingLevel = GetValue("Enter Striking Level: ");
int grapplingLevel = GetValue("Enter Grappling Level: ");
int submissionLevel = GetValue("Enter Submission Level: ");
int durabilityLevel = GetValue("Enter Durability Level: ");
int technicalLevel = GetValue("Enter Technical Level: ");
int speedLevel = GetValue("Enter Speed Level: ");
int hardcoreLevel = GetValue("Enter Hardcore Level: ");
int charismaLevel = GetValue("Enter Charisma Level: ");
int total = strikingLevel + grapplingLevel + durabilityLevel + submissionLevel +
technicalLevel + speedLevel + charismaLevel + hardcoreLevel;
int overall = total / 8 + 8;
Console.WriteLine("\nThe Overall is {0}.", overall);
while (true)
{
Console.WriteLine("Do you wish to continue? y/n? ");
string response = Console.ReadLine();
if (response.Equals("y", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = true;
break;
}
else if (response.Equals("n", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = false;
break;
}
}
}
}
private static int GetValue(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
string input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if (value <= 0)
Console.WriteLine("Please enter a positive number.");
else
return value;
}
else
{
Console.WriteLine("Please enter a number.");
}
}
}
}
}
Yes... before you do anything calculations, you need to validate the data you are going to use. If any data is incorrect, then you display a messagebox detailing the errors and return focus to the form so the user can fix the errors. Repeat as necessary.
I wrote this one many moons ago when I first learned C#. It is a conversion from a VB function that I got back in VB5 days. The major benefit of the function is that there is no error - an input will just not allow any characters outside of the predefined list.
/***********************************************************************
* bool ValiText(char inChar,
* string valid,
* bool editable,
* bool casesensitive
* Description: Validate Input Characters As They Are Input
* Notes: For each control whose input you wish to validate, just put
* e.Handled = ValiText(e.KeyChar, "0123456789/-" [,true][,true])
* In The KeyPress Event
***********************************************************************/
public bool ValiText(char inChar, string valid, bool editable, bool casesensitive)
{
string inVal = inChar.ToString();
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
/// Case InSensitive - Make Them Both The Same Case
if (!casesensitive)
{
tst = tst.ToLower();
inVal = inVal.ToLower();
}
return tst.IndexOf(inVal,0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid, bool editable)
{
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
return tst.IndexOf(inChar.ToString(),0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid)
{
return valid.IndexOf(inChar.ToString(),0,valid.Length) < 0;
}
Note That This Will Not Work On A Web APP.

Categories