I have this question that I have to do for an assignment for school. I am having troubles making it work with decimals. If someone could help me get the program to accept decimals. It will output a decimal but it won't let me input one.
using System;
public class Bank_Account
{
public static void Main()
{
char input, C, D, P, Q;
double balance;
Console.WriteLine("Please enter C for Cheque, D for Deposit, P for Print or Q to quit");
input = Convert.ToChar(Console.ReadLine());
do
{
switch (input)
{
case 'D':
Deposit(ref balance);
break;
case 'P':
Print(balance);
break;
case 'C':
Cheque(ref balance);
break;
default:
Console.WriteLine("{0} is not a valid choice", input);
break;
}
} while (input != 'Q');
}
public static void Deposit(ref double balance)
{
double deposit;
Console.WriteLine("Enter the amount you want to deposit: ");
deposit = Convert.ToInt32(Console.ReadLine());
if (deposit > 1000)
{
deposit = deposit*1.02;
}
else
{
deposit = deposit;
}
balance = +deposit;
}
public static void Cheque(ref double balance)
{
var tempBalance = balance;
double deduction;
const double fee = 1;
do
{
Console.WriteLine("Enter the amount of the cheque: ");
deduction = Convert.ToInt32(Console.ReadLine());
} while (deduction < 0);
tempBalance = balance - deduction - fee;
if (tempBalance < 0)
{
Console.Write("Not enough money in the account");
}
else
{
balance = tempBalance;
}
}
public static void Print(double balance)
{
Console.WriteLine("Your current balance is {0.00}", balance);
}
}
Change this:
deposit = Convert.ToInt32(Console.ReadLine());
to:
deposit = Convert.ToDouble(Console.ReadLine());
since you're not reading an int, but a double. Using TryParse like suggested in another answer would be even better. Also, maybe you should be using decimal and not double if you need exactness, but double if accuracy is less of a concern.
You are converting to Int, change like this,
do
{
Console.WriteLine("Enter the amount of the cheque: ");
deduction = Convert.ToDouble(Console.ReadLine());
}
Try This:
double deposit;
double.TryParse(Console.ReadLine(),out deposit);
deposit = Double.Parse(Console.ReadLine());
Related
using System;
namespace ConsoleApp1
{
class program
{
public static void Main()
{
int qty;
double price;
Console.WriteLine("please enter the qty");
qty = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("please enter the price ");
price = Convert.ToDouble(Console.ReadLine());
double total = price * qty;
Console.WriteLine($"tota is : {total:c}");
Console.ReadKey();
}
}
}
output
please enter the qty
3
please enter the price
12.44
error message after entering double: 12.44
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Convert.ToDouble(String value)
at ConsoleApp1.program.Main() in C:\Users\Baba\Desktop\C#\ConsoleApp1\ConsoleApp1\Program.cs:line 14
Welcome to SO! In addition to #PaulSinnema 's input: you could try TryParse() to detect/ avoid invalid user input:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//int qty;
//double price;
Console.WriteLine("please enter the qty");
//qty = Convert.ToInt32(Console.ReadLine());
var input = Console.ReadLine();
if (!Int32.TryParse(input, out int qty))
{
Console.WriteLine($"invalid input \"{input}\"");
Console.ReadKey();
return;
}
Console.WriteLine("please enter the price ");
//price = Convert.ToDouble(input);
input = Console.ReadLine();
if (!double.TryParse(input, out double price))
{
Console.WriteLine($"invalid input \"{input}\"");
Console.ReadKey();
return;
}
double total = price * qty;
Console.WriteLine($"total is : {total:c}");
Console.ReadKey();
}
}
}
So i am trying to return the discount amount between 2 .cs files into the main and print out the amount there instead of doing it on the second class. I am pretty new at this and i need help
code is not yet complete
MAIN
using System;
namespace CalcDiscount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter price");
double input = double.Parse(Console.ReadLine());
Calculator myCalculator = new Calculator();
myCalculator.Calculation(input);
Console.WriteLine("Enter discount");
input = double.Parse(Console.ReadLine());
Console.WriteLine("");
Console.ReadLine();
}
}
}
SECOND FILE
calculator.cs
using System;
namespace CalcDiscount
{
public class Calculator
{
public void Calculation(double input)
{
Console.WriteLine("Your entered the number: " + input);
int i = 1;
if (input != 0)
{
Console.WriteLine(input + " x " + i + " = " + input * i);
}
}
}
}
You could change the method Calculation in your Calculator class, from void to double. The method will calculate the result and return it to the main function, where it will be printed.
Calculation method:
public double Calculation(double input1, double input2)
{
return (input1 * input2);
}
Main:
Console.WriteLine("Enter first input");
double input1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second input");
double input2 = double.Parse(Console.ReadLine());
Calculator myCalculator = new Calculator();
double result = myCalculator.Calculation(input1, input2);
Console.WriteLine("result = " + result);
public class Calculator
{
public double Calculation(double input)
{
Console.WriteLine("Your entered the number: " + input);
int i = 1;
double result = 0;
if (input != 0)
{
result = i * input;
}
return result;
}
}
I made here a few changes
changed the return type to double (because you send double so it logical to return the same type but not necessary
add a result variable to return the result
did the calculation ( result = i * input)
return the result
note that if i == 0 the result will be 0, because result is initialized to zero, but can apply any logic that you want
and in your Main i read the result from the function and output it to the Console
double result = myCalculator.Calculation(input);
Console.WriteLine("caculcation result is" + result);
How do I write the pseudocode for a switch (case) statement in C#?
switch (option)
{
case 1:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 + num2;
Console.WriteLine(result);
break;
case 2:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 - num2;
Console.WriteLine(result);
break;
case 3:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 * num2;
Console.WriteLine(result);
break;
default:
Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
break;
}
So, if I was going to write this, I'd start with an enumerated type for the operations:
public enum ArithmeticOperation
{
Add,
Subtract,
Multiply,
Divide,
}
I'd write a little helper function:
private static string ShowEnumOptions<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException($"Type: {typeof(T).ToString()} must be an enumerated type");
}
var options = Enum.GetNames(typeof(T));
return string.Join("/", options);
}
(the newest version of C# (which I don't use yet) allows a System.Enum constraint on a generic type parameter which would simplify this)
Then I'd write my main program to look like this:
static void Main(string[] args)
{
while (true)
{
ArithmeticOperation operation = default(ArithmeticOperation);
var goodOperation = false;
while (!goodOperation)
{
Console.Write(
$"Enter operation (one of [{ShowEnumOptions<ArithmeticOperation>()}] or \"Quit\"): ");
var response = Console.ReadLine();
if (string.Equals(response, "Quit", StringComparison.InvariantCultureIgnoreCase))
{
return; //quit the app
}
if (Enum.TryParse<ArithmeticOperation>(response, true, out operation))
{
goodOperation = true;
}
}
double value1 = 0.0;
double value2 = 0.0; //initialize them to keep the compiler happy
var goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the first number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value1))
{
goodDouble = true;
}
}
goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the second number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value2))
{
goodDouble = true;
}
}
//ok, got an operation and two numbers
double result = 0.0;
switch (operation)
{
case ArithmeticOperation.Add:
result = value1 + value2;
break;
case ArithmeticOperation.Subtract:
result = value1 - value2;
break;
case ArithmeticOperation.Multiply:
result = value1 * value2;
break;
case ArithmeticOperation.Divide:
if (value2 == 0.0)
{
Console.WriteLine("Division by zero is invalid");
result = double.NaN; //NaN means "not a number"
break;
}
result = value1 / value2;
break;
}
Console.WriteLine($"Result is {result}");
}
}
Note that I check all input for validity. Always assume your users will enter bad data. Also note that I check my double for equality with zero. Checking for floating point equality is usually a bad idea, but it's the right thing to do here.
Then, as pseudo code, all I'd write would be:
// Get the operation (one of add/subtract/multiply or divide) - or allow the user to quit
// Get each of value1 and value2 as doubles
// Based on the operation, calculate the result (pay attention to division by zero)
// Show the result
// Loop back and let the user try again (or quit)
Pseudocode is basically writing what you're trying to do in comments. What your professor was probably trying to teach you is to make a bunch of comments to plan out the structure of your code, and then write your code. What you have above is already functional code. At the risk of answering your homework question, I'd say it goes something like this:
switch(option)
{
case 1:
//do something
break;
case 2:
//do something else
break;
default:
//what to do if none of the cases are met
break;
}
I don't know what you mean with pseudocode but this code is less repetitive:
double result = 0;
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter a number from 1 to 3");
string input = Console.ReadLine();
switch (input) {
case "1" :
result = num1 + num2;
break;
case "2":
result = num1 - num2;
break;
case "3":
result = num1 * num2;
break;
default:
Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
break;
}
Console.WriteLine("Result = " + result);
So this is my budget calculator.
It calculates how much i can earn with deposit(% per year), i can add money(earnings) and can decrease money(loosing).
In my code you have to manually tell the size of starting money.
What i need is for example in the beginning i tell my program that starting capital is 500euro. When i use deposit, it become for example 570,50. When i use earnings, i need it to start from 570,50, but in my program it will always ask again, what is your starting capital. I need to do it automatically somehow. Sorry for my bad english and here is the whole code :)
class Program
{
static void Main(string[] args)
{
int menu;
do
{
Console.WriteLine("1 - '%'");
Console.WriteLine("2 - '+'");
Console.WriteLine("3 - '-'");
Console.WriteLine("0 - iziet");
Console.Write("Menu: ");
menu = Convert.ToInt32(Console.ReadLine());
if (menu > 0 && menu < 4)
{
switch (menu)
{
case 1:
{
Console.Write("Noguldamā naudas summu: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Procentu likme (0 - 100): ");
int b = Convert.ToInt32(Console.ReadLine());
Console.Write("Laiks (gadi): ");
int c = Convert.ToInt32(Console.ReadLine());
double d = Procenti(a, b, c);
Console.WriteLine("\nNaudas summa pēc {0} gadiem būs {1}\n", c, d);
}
break;
case 2:
{
Console.Write("Sakuma nauda: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Cik nopelnijat: ");
int b = Convert.ToInt32(Console.ReadLine());
double d = Pluss(a, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", d);
}
break;
case 3:
{
Console.Write("Sakuma nauda: ");
double a = Convert.ToDouble(Console.ReadLine());
Console.Write("Cik izterejat: ");
double b = Convert.ToDouble(Console.ReadLine());
double d = Minuss(a, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", d);
}
break;
}
}
else
{
Console.WriteLine();
Console.WriteLine("Ludzu ievadiet ciparus 0,1,2,3 - parejie cipari ir arpus robezham!");
Console.WriteLine();
}
} while (menu != 0);
}
//FUNKCIJASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
static double Procenti(double a, double b, int c)
{
for (int i = 0; i < c; i++)
{
a = (a * (b / 100) + a);
}
return a;
}
static double Pluss(double a, double b)
{
return a + b;
}
static double Minuss(double a, double b)
{
return a - b;
}
}
you need to store the value inside a variable.
and before to start the transactions you ask the user for the value :
int menu;
float stored_money;
Console.Write("Enter the Initial Value: ");
stored_money = Convert.ToInt32(Console.ReadLine());
do
{
and in the functions use this variable
static double Pluss(double b)
{
stored_money = stored_money + b;
return stored_money;
}
static double Minuss(double b)
{
stored_money = stored_money - b;
return stored_money;
}
Well, basically it looks like you need to save your balance amount somewhere in your code, because right now you're entering it from console in each menu point.
Something like (note I've omitted most of code):
int menu;
decimal amount;
do
{
.... //your code
case 1:
{
Console.Write("Noguldamā naudas summu: ");
amount = Convert.ToDecimal(Console.ReadLine());
.... //your code
decimal d = Procenti(a, b, c);
amount += d;
}
case 2:
{
Console.Write("Cik nopelnijat: ");
decimal b = Convert.ToInt32(Console.ReadLine());
amount = Pluss(amount, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", amount);
}
.... //your code
} while (menu != 0);
And later in all cases you should not enter amount, but use that saved value and modify it according to menu point task.
Or maybe you even should introduce new menu point to set initial amount and don't enter it in point 1 (if point 1 can be called multiple times) - it depends on your calculator logic and it's up to you.
Note - it's better to use decimal rather that int and double for financial calculations as it is designed to store full possible precision.
I'm pretty new to c# and am confused on how to set the data members and then calculate the tax with a different method. Here is what this part of the program should do:
"If the user selects default the default values you will instantiate a rates object using the default constructor and set the Taxpayer class data member for tax equal to the value returned from calling the rates object CalculateTax method."
-I have a switch statement calling for the default constructor if they choose 'D', I'm not sure how to set the taxpayer class data to default, i'm not sure if the CalculateTax method is correct either.
and then do the same type of thing if they choose 'O'
Here is what I have so far:
using System;
interface Icomparable
{
int CompareTo(Object o);
}
class rates
{
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
private rates()
{
Limit = 30000;
LowRate = 0.15;
HighRate = 0.28;
}
public rates(double Limit; double LowRate; double HighRate;)
{
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
}
public CalculateTax()
{
if(Income < Limit)
{TaxOwed = (Income * LowRate)}
else
{TaxOwed = (Income * HighRate)}
}
}
public class taxpayer : IComparable
{
public string SSN{get; set;}
public double Income{get; set;}
public double TaxOwed{get;}
int IComparable.CompareTo(Object o)
{
int returnVal;
taxpayer temp = (taxpayer)o;
if(this.TaxOwed > temp.TaxOwed)
returnVal = 1;
else
if(this.TaxOwed < temp.TaxOwed)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
public getRates()
{
double Limit;
double LowRate;
double HighRate;
Console.WriteLine("Do you want default values(enter D) or enter your own (enter O)?");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case'D':
rates();
break;
case'O':
rates(double Limit; double LowRate; double HighRate;)
break;
default:
Console.WriteLine("Invalid input");
goto getRates();
}
}
}
Any help with this would be very much appreciated.
I don't see why you would keep re creating an object that you have all the values for.
Here is an alternate pattern, static presets + factory
class Rates
{
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
static readonly Rates default = new Rates(30000,0.15,0.28);
static readonly Rates govna = new Rates(300000,0.1,0.2);
static readonly Rates priest = new Rates(300,0.05,0.07);
public static Rates createRates()
{
double Limit; double LowRate; double HighRate;
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
return new Rates( Limit, LowRate, HighRate );
}
private Rates(double limit; double lowRate; double highRate;)
{
Limit = limit;
LowRate = lowRate;
HighRate = highRate;
}
public double CalculateTax( double Income)
{
if(Income < Limit)
{return (Income * LowRate)}
else
{return (Income * HighRate)}
}
}
Oh and whats with goto?
while( null == ratesResult ){
Console.WriteLine("Do you want default values(enter D) or enter your own (enter O)?");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case'D':
ratesResult = Rates.default;
break;
case'O':
ratesResult = Rates.createRates();
break;
default:
Console.WriteLine("Invalid input");
}
}
You have many problems with your code, buddy. Here is some advice that might guide you in the right direction.
In the following properties, you should also have a set; accessor to be able to store those values.
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
In the following function, do you want to prompt the user to enter values? If so, change the first line from
public rates(double Limit; double LowRate; double HighRate;)
to
public rates(bool dummy)
Now your code will look like
public rates(bool dummy) //Note that dummy is not used in this function. It just distinguishes rates() from rates(bool)
{
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
}
the dummy is just to allow the the code to distinguish your two different functions.
In your switch statement, just call the rates(bool dummy) function instead of the other one. For the dummy, assign it either true or false, who cares.... It'd look like the following.
switch (entry) //set switch
{
case'D':
rates();
break;
case'O':
rates(true)
break;
default:
Console.WriteLine("Invalid input");
goto getRates();
}
There's more problems with your code, but you have to revise it before we can help you further. You should actually try to use it in VS, since the editor can help you fix problems by giving you specific errors.