Console.Write("Input price: ");
double price;
string inputPrice = Console.ReadLine();
if (double.TryParse(inputPrice, out price))
{
price = double.Parse(inputPrice);
}
else
{
Console.WriteLine("Inventory code is invalid!");
}
so i have to make sure that the price that will be inputed has and must be 2 decimal places. Such as the following:
2.00 - correct
3.65 - correct
77.54 - correct
34.12 - correct
but
2 - wrong
2.8 - wrong
2.415 - wrong
99.0 - wrong
how should i check for it it?
Try this:-
Console.Write("Input price: ");
double price;
string inputPrice = Console.ReadLine();
var num = Decimal.Parse(inputPrice); //Use tryParse here for safety
if (decimal.Round(num , 2) == num)
{
//You pass condition
}
else
{
Console.WriteLine("Inventory code is invalid!");
}
Update
Regex Check:-
var regex = new Regex(#"^\d+\.\d{2}?$"); // ^\d+(\.|\,)\d{2}?$ use this incase your dec separator can be comma or decimal.
var flg = regex.IsMatch(inputPrice);
if(flg)
{
\\its a pass
}
else
{
\\failed
}
check inputPrice.Split('.')[1].Length == 2
UPDATE:
Console.Write("Input price: ");
double price;
string inputPrice = Console.ReadLine();
if (double.TryParse(inputPrice, out price) && inputPrice.Split('.').Length == 2 && inputPrice.Split('.')[1].Length == 2)
{
price = double.Parse(inputPrice);
}
else
{
Console.WriteLine("Inventory code is invalid!");
}
Related
I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.
The problem I have is that it only remember the last number entered, which would be -1. What would I have to do to fix this?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
} while (price != -1);
subtotal = Convert.ToInt32(price);
Console.Write("Subtotal: ${0}", subtotal);
}
}
}
Try this variation to Artem's answer. I think this is a little cleaner.
int count = 0;
decimal input = 0;
decimal price = 0;
while (true)
{
Console.Write("Item {0} Enter Price: ", count++);
input = Convert.ToDecimal(Console.ReadLine());
if (input == -1)
{
break;
}
price += input;
}
In each iteration of the loop, you overwrite the value of price. Separate input and storage price.
decimal input = 0;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
input = Convert.ToDecimal(Console.ReadLine());
if (input != -1)
price += input;
} while (input != -1);
Use a list and keep adding the entries to the list.
Or you can keep a running total in another integer.
Something like:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
Please try to use this
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal = 0m; //subtotal is needed to be initialized from 0
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
if (price != -1) //if the console input -1 then we dont want to make addition
subtotal += price;
} while (price != -1);
//subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total
}
}
}
Hi I'm having trouble with an error "No overload method 'conversationOutput' takes '2' arguments" please help. I'm having a little trouble understanding method calling, and calling variables from main().
class MainClass
{
static void Main ()
{
string selection;
double values;
selection = userChoice();
values = userInput(selection);
conversationOutput(selection, values);
}
static string userChoice ()
{
string choose;
Console.WriteLine("Welcome to the OHM's law calculator! \n \nWhat would you like to calcualte?");
Console.WriteLine("1. Voltage:");
Console.WriteLine("2. Current:");
Console.WriteLine("3. Resistance:");
do
{
choose = Console.ReadLine();
if (choose != "1" && choose != "2" && choose != "3")
{
Console.WriteLine("Please only select '1' for voltage, '2' for current, '3' resistance");
}
} while (choose != "1" && choose != "2" && choose != "3");
switch (choose)
{
case "1":
Console.Write("You have choose to calculate Voltage.\n");
break;
case "2":
Console.Write("You have choose to calculate Current.\n");
break;
case "3":
Console.WriteLine("You have choose to calculate Resistance.\n");
break;
}
return choose;
}
static double userInput (string choose)
{
double voltageD = 0.0;
double currentD = 0.0;
double resistanceD = 0.0;
string current;
string voltage;
string resistance;
bool ok = true;
do if (choose != "1")
{
do
{
Console.WriteLine("Please enter your value for Voltage (volts)...");
voltage = Console.ReadLine();
ok = double.TryParse(voltage, out voltageD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (voltageD < 0)
{
Console.WriteLine("Please select a number larger than the lower limit of 0 volts");
}
} while (voltageD < 0);
do if (choose != "2")
{
do
{
Console.WriteLine("Please enter your value for Current (amp)...");
current = Console.ReadLine();
ok = double.TryParse(current, out currentD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (currentD < 0.01)
{
Console.WriteLine("Please select a number larger than the lower limit of 0.01 amp");
}
} while (currentD < 0.01);
do if (choose != "3")
{
do
{
Console.WriteLine("Please enter your value for Resistance (ohm)...");
resistance = Console.ReadLine();
ok = double.TryParse(resistance, out resistanceD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (resistanceD < 10)
{
Console.WriteLine("Please select a number larger than the lower limit of 10 ohm");
}
} while (resistanceD < 10);
return 0;
}
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
{
/* v = i*r */
double output = 0.0;
string units = "";
if (choose == "1")
{
output = (currentD) * (resistanceD);
units = "Volts";
}
if (choose == "2")
{
output = (voltageD) / (resistanceD);
units = "Amps";
}
if (choose == "3")
{
output = (voltageD) / (resistanceD);
units = "OHM";
}
Console.WriteLine("The calculated value is {0:F3} {1:F3}", output, units);
return 0;
}
}
The reason is you have a method
double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
which has 4 parameters and you are passing only 2 parameters to the method.
define the missing parameters as optional
static double conversationOutput (string choose, double currentD, double voltageD =0, double resistanceD =1)
As per the method definition, conversationOutput expects four parameters.
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD) {}
But you are calling it by passing just two parameters.
conversationOutput(selection, values);
That's why you are getting such error.
It will work if you call the conversationOutput method by passing four parameters.
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.
I would like to validate my input as bigger than or equal to 0 and as double. This is what i have so far:
string aBalBeginS;
double abalbeginVal;
Console.Write("Account Balance at the beginning: $");
aBalBeginS = Console.ReadLine();
abalbeginVal = double.Parse(aBalBeginS);
if (aBalBeginS == "" || abalbeginVal <= 0)
{
Console.WriteLine("Invalid data entered - no value redorded");
aBalBeginS = null;
}
How do i add to check if input is a number. I tried double.TryParse, but without luck.
You are on the right track with double.TryParse()
double abalbeginVal;
bool parsed = double.TryParse(aBalBeginS, out abalbeginVal);
if (parsed && abalbeginVal >=0.0)
{
// We're good
}
else
{
// Did not pass check
}
Found the solution:
Console.Write("Account Balance at the beginning: $");
aBalBeginC = Console.ReadLine();
//abalbeginVal = double.Parse(aBalBeginC);
if (double.TryParse(aBalBeginC, out abalbeginVal) == false || aBalBeginC == "" || abalbeginVal <= 0)
{
Console.WriteLine("Invalid data entered - no value redorded");
aBalBeginC = null;
}
Thx.
This question already has answers here:
Why did I get the compile error "Use of unassigned local variable"?
(10 answers)
Closed 4 days ago.
I keep getting this error for annualRate, monthlyCharge, and lateFee.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab_5___Danny_Curro
{
class Program
{
static void Main(string[] args)
{
string firstName;
string lastName;
int accNumber;
string creditPlan;
double balance;
string status;
Boolean late = false;
double lateFee;
double monthlyCharge;
double annualRate;
double netBalance;
Console.Write("Enter First Name: ");
firstName = Console.ReadLine();
Console.Write("Enter Last Name: ");
lastName = Console.ReadLine();
Console.Write("Enter Account Number: ");
accNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Credit Card Plan Number[Blank Will Enter Plan 0]: ");
creditPlan = Console.ReadLine();
Console.Write("Enter Balance: ");
balance = Convert.ToDouble(Console.ReadLine());
Console.Write("Is This Account Late?: ");
status = Console.ReadLine().Trim().ToLower();
if (creditPlan == "0")
{
annualRate = 0.35; //35%
lateFee = 0.0;
monthlyCharge = balance * (annualRate * (1 / 12));
return;
}
if (creditPlan == "1")
{
annualRate = 0.30; //30%
if (status == "y")
{
late = true;
}
else if (status == "n")
{
late = false;
}
if (late == true)
{
lateFee = 25.00;
}
monthlyCharge = balance * (annualRate * (1 / 12));
return;
}
if (creditPlan == "2")
{
annualRate = 0.20; //20%
if (status == "y")
{
late = true;
}
else if (status == "n")
{
late = false;
}
if (late == true)
{
lateFee = 35.00;
}
if (balance > 100)
{
monthlyCharge = balance * (annualRate * (1 / 12));
}
else
{
monthlyCharge = 0;
}
return;
}
if (creditPlan == "3")
{
annualRate = 0.15; //15%
lateFee = 0.00;
if (balance > 500)
{
monthlyCharge = (balance - 500) * (annualRate * (1 / 12));
}
else
{
monthlyCharge = 0;
}
return;
}
netBalance = balance - (lateFee + monthlyCharge);
Console.WriteLine("Name: \t\t\t {0} {1}", firstName, lastName);
Console.WriteLine("Account Number: \t{0}", accNumber);
Console.WriteLine("Credit Plane: \t\t{0}",creditPlan);
Console.WriteLine("Account Late: \t\t{0}", late);
Console.WriteLine("Balance: \t\t{0}", balance);
Console.WriteLine("Late Fee: \t\t{0}", lateFee);
Console.WriteLine("Interest Charge: \t{0}", monthlyCharge);
Console.WriteLine("Net Balance: \t\t{0}",netBalance);
Console.WriteLine("Annual Rate: \t\t{0}", annualRate);
Console.ReadKey();
}
}
}
The compiler isn't smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn't see that variables like annualRate will be assigned no matter what. Here's how you can make the compiler understand:
if (creditPlan == "0")
{
// ...
}
else if (creditPlan == "1")
{
// ...
}
else if (creditPlan == "2")
{
// ...
}
else
{
// ...
}
The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.
By the way, you can also use a switch statement instead of ifs to maybe make your code cleaner.
Change your declarations to this:
double lateFee = 0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
The error is caused because there is at least one path through your code where these variables end up not getting set to anything.
Because if none of the if statements evaluate to true then the local variable will be unassigned. Throw an else statement in there and assign some values to those variables in case the if statements don't evaluate to true. Post back here if that doesn't make the error go away.
Your other option is to initialize the variables to some default value when you declare them at the beginning of your code.
Give them a default value:
double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
Basically, all possible paths don't initialize these variables.
Use the keyword "default"!!!
string myString = default;
double myDouble = default;
if(!String.IsNullOrEmpty(myString))
myDouble = 1.5;
return myDouble;
There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.
Specifically, you are not validating the user input for creditPlan - if the user enters a value of anything else than "0","1","2" or "3", then none of the branches indicated will be executed (and creditPlan will not be defaulted to zero as per your user prompt).
As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else statement).
I would however like to point out other potential improvements:
Validate user input before you trust it for use in your code.
Model the parameters as a whole - there are several properties and calculations applicable to each plan.
Use more appropriate types for data. e.g. CreditPlan appears to have a finite domain and is better suited to an enumeration or Dictionary than a string. Financial data and percentages should always be modelled as decimal, not double to avoid rounding issues, and 'status' appears to be a boolean.
DRY up repetitive code. The calculation, monthlyCharge = balance * annualRate * (1/12)) is common to more than one branch. For maintenance reasons, do not duplicate this code.
Possibly more advanced, but note that Functions are now first class citizens of C#, so you can assign a function or lambda as a property, field or parameter!.
e.g. here is an alternative representation of your model:
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
Your assignments are all nested within your conditional if blocks which means that there is potential for them to never be assigned.
At the top of your class, initialise them to 0 or some other value
The compiler is saying that annualRate will not have a value if the CreditPlan is not recognised.
When creating the local variables ( annualRate, monthlyCharge, and lateFee) assign a default value (0) to them.
Also, you should display an error if the credit plan is unknown.
Not all code paths set a value for lateFee. You may want to set a default value for it at the top.
You don't assign values outside of the if statements ... and it is possible that credit might be something other than 0, 1, 2, or 3, as #iomaxx noted.
Try changing the separate if statements to a single if/else if/else if/else. Or assign default values up at the top.
If you declare the variable "annualRate" like
class Program
{
**static double annualRate;**
public static void Main() {
Try it..