C# Program Validation - c#

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.

Related

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# IF/ELSE statemenets

I need help with some of my code for a game calculator. So I wrote all this code, but the IF/THEN statement is acting weird.
Screenshot:
-
I typed in P and it should have gone to the ELSE part of the code, but instead it continued onto the if part. Please help!
{
class MainClass
{
public static void Main(string[] args) // IF YOU ARE TO REWRITE FROM MY SOURCE, ALL ORIGINAL CREDITORS MUST GO INTO THE CREDITS!
{
double num01;
double num02;
double num03;
double num04;
double num05;
double num06;
string CD = null;
string P = null;
string answer = null;
Console.Write("Diogenes's Calculator 1.0\n\nCredits: DoS (#57714)\n DZ(#54689)");
Console.WriteLine();
Console.WriteLine();
Console.Write("Hello! Would you like Charity Donation or Propaganda Calculator? (CD or P): ");
Console.ReadLine();
answer = Convert.ToString();
if(answer == CD) {
Console.WriteLine();
Console.Write("Howmuch influence does the target have?: ");
num01 = Convert.ToDouble(Console.ReadLine());
Console.Write("Howmuch is the cost of Charity Donatins? (Gold): ");
num02 = Convert.ToDouble(Console.ReadLine());
Console.Write("What % of influence does Charity Donation give (Made if value does change)?: ");
num03 = Convert.ToDouble(Console.ReadLine());
Console.Write(num02 + num03);
Console.ReadKey();
} else if(answer == P) {
answer = Convert.ToString();
Console.WriteLine();
Console.Write("Howmuch influence does the target have?: ");
num04 = Convert.ToDouble(Console.ReadLine());
Console.Write("Howmuch influence do you want the target to have?: ");
num05 = Convert.ToDouble(Console.ReadLine());
Console.Write("What % of influence does Propaganda take off (Made if value does change)?: ");
num06 = Convert.ToDouble(Console.ReadLine());
Console.Write(num04 + num05);
Console.ReadKey();
} else {
Console.WriteLine("Looks like you didn't type in CD or P. Buh Bye!");
Console.ReadKey();
}
}
}
}
you are checking if answer is equal to the value stored in the field P, not if answer is equal to the actual string "P". And P the variable is null.
Secondly, you are throwing away your user input here:
Console.ReadLine();
answer = Convert.ToString();
you are reading the console input into nothing, then assigning answer to the Convert object's string representation, which is probably a fully qualified namespace. You want:
answer = Console.ReadLine();
Console.Write("Hello! Would you like Charity Donation or Propaganda Calculator? (CD or P): ");
answer = Console.ReadLine();
if(answer == "CD") {

C# the variable UserInput cannot find the definition

double UserInput;
string y, z;
double OunceToGram, PoundToOunce, PoundToKilogram, PintToLitre, InchToCenti, MilesToInch;
OunceToGram = UserInput * 28.0; //(error is here, it cannot find UserInput)
PoundToOunce = UserInput * 16.0;
PoundToKilogram = UserInput * 0.454;
PintToLitre = UserInput * 0.568;
InchToCenti = UserInput * 2.5;
MilesToInch = UserInput * 63360.0;
int i = 0;
while (i < UserInput)
{
Console.WriteLine("");
Console.WriteLine("Please enter a unit to convert, type a num <1 to cancel");
UserInput = Convert.ToDouble(Console.ReadLine());
You could resolve your problem not converting immediately the user input to your variable UserInput and checking if the user types a conventional letter to stop the input
double UserInput = 0.0; // <- You need to initialize before using it ...
.....
string stopInput = "N";
while (stopInput != "Q"))
{
Console.WriteLine("");
Console.WriteLine("Please enter a unit to convert, type 'Q' to cancel");
stopInput = Console.ReadLine();
if(stopInput == "Q")
break;
UserInput = Convert.ToDouble(stopInput);
....
}

Converting Char to Uppercase From User Inputted Data

I am trying to create a program for a hotel where the user is to enter a character (either S, D, or L) and that is supposed to correspond with a code further down the line. I need help converting the user input (no matter what way they enter it) to be converted to uppercase so I can then use an if statement to do what I need to do.
My code so far is the following:
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
**^Right Her is Where I Want To Convert To Uppercase^**
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
public static double RoomCharge(int NumDays, char RoomType)
{
double Charge = 0;
if (RoomType =='S')
Charge = NumDays * 80.00;
if (RoomType =='D')
Charge= NumDays * 125.00;
if (RoomType =='L')
Charge = NumDays * 160.00;
Charge = Charge * (double)NumDays;
Charge = Charge * 1.13;
return Charge;
}
Try default ToUpper method.
roomtype = Char.ToUpper(roomtype);
Go through this http://msdn.microsoft.com/en-us/library/7d723h14%28v=vs.110%29.aspx
roomtype = Char.ToUpper(roomtype);
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
roomtype = Char.ToUpper(roomtype);
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}

Manipulating user input (Mathematical)

I'm using C#. I am trying to allow the user to input a numerical value (IE: how many do you want?) and then take that value and figure tax and total. I can not figure out how to do this and wondered if anyone could show me? My current script is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Infinate Happiness Ranch.\nPlease enter your order information bellow. ");
Console.WriteLine();
Console.WriteLine("Please enter your first and last name:");
string FirstName = Console.ReadLine();
Console.WriteLine("Please enter your street address:");
string Address = Console.ReadLine();
Console.WriteLine("Please enter your city:");
string City = Console.ReadLine();
Console.WriteLine("Please enter your two letter state abbreviation:");
string StateCode = Console.ReadLine();
Console.WriteLine("Please enter your zip code:");
string ZipCode = Console.ReadLine();
Console.WriteLine("Please enter the number of Tribbles \nyou wish to purchase for $29.99 plus tax");
string NumberOrdered = Console.ReadLine();
Console.WriteLine("Invoice \nName {0}", FirstName);
Console.WriteLine("Address {0}", Address);
Console.WriteLine("City {0}", City);
Console.WriteLine("StateCode {0}", StateCode);
Console.WriteLine("ZipCode {0}", ZipCode);
Console.WriteLine("NumberOrdered {0}", NumberOrdered);
// PROGRAM WORKS UNTIL HERE.
NumberOrdered = m;
TotalBeforeTax = m * 29.99; //'n' is total b4 tax
o = n * 0.9;// 'o' is total tax due
p = o + n; // 'p' is total due
Console.WriteLine("Your total is {0} {1}", n);
Console.WriteLine("Your tax is {0}", o);
Console.WriteLine("Your total charge is {0}", p);
Console.WriteLine("Thank you for your order");
Console.WriteLine();
//Console.WriteLine("Name:" + FirstName);
Console.Read();
}
}
}
You should parse the string with
int ordered = int.Parse(NumberOrdered);
And continue to calculate with this integer.
Because the user is entering information as strings, you should convert the number ordered to an integer. Also, to preserve your decimals, you need to store numbers as doubles for things such amounts.
int numOrdered = Convert.ToInt32(NumberOrdered);
double TotalBeforeTax = numOrdered * 29.99;
double beforeTax = TotalBeforeTax * 0.9;
double afterTax = beforeTax + TotalBeforeTax;
Console.WriteLine("Your total is {0}", TotalBeforeTax);
Console.WriteLine("Your tax is {0}", beforeTax);
Console.WriteLine("Your total charge is {0}", afterTax);
Console.WriteLine("Thank you for your order");
You forgot to declare some variables and assign some values​​.
Try this:
static float m;
static float n;
static float o;
static float p;
static float TotalBeforeTax;
static void Main(string[] args)
{
Console.WriteLine("Welcome to Infinate Happiness Ranch.\nPlease enter your order information bellow. ");
Console.WriteLine();
Console.WriteLine("Please enter your first and last name:");
string FirstName = Console.ReadLine();
Console.WriteLine("Please enter your street address:");
string Address = Console.ReadLine();
Console.WriteLine("Please enter your city:");
string City = Console.ReadLine();
Console.WriteLine("Please enter your two letter state abreviation:");
string StateCode = Console.ReadLine();
Console.WriteLine("Please enter your zip code:");
string ZipCode = Console.ReadLine();
Console.WriteLine("Please enter the number of Tribbles \nyou wish to purchase for $29.99 plus tax");
string NumberOrdered = Console.ReadLine();
Console.WriteLine("Invoice \nName {0}", FirstName);
Console.WriteLine("Address {0}", Address);
Console.WriteLine("City {0}", City);
Console.WriteLine("StateCode {0}", StateCode);
Console.WriteLine("ZipCode {0}", ZipCode);
Console.WriteLine("NumberOrdered {0}", NumberOrdered);
//PROGRAM WORKS UNTIL HERE ? HELP ? ? ? ? ?
//NumberOrdered = m;
m = float.Parse(NumberOrdered);
TotalBeforeTax = m * 29.99f; //'n' is total b4 tax
n = TotalBeforeTax;
o = n * 0.9f;//'o' is total tax due
p = o + n; //'p' is total due
Console.WriteLine("Your total is {0}", n);
Console.WriteLine("Your tax is {0}", o);
Console.WriteLine("Your total charge is {0}", p);
Console.WriteLine("Thank you for your order");
Console.WriteLine();
Console.Read();
}
Hope this helps !
Just a bit of advice, you can include non-string variables in Console.WriteLine() like:
Console.WriteLine("Your tax is " + o);
This is what most professional developers do. No need for complicated C/C++ style of parsing.
Also, you don't seem to be declaring the variables o and p. Try this:
double o = Convert.toDouble(n * 0.9);
or
double o = (double)(n * 0.9);

Categories