Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having a little trouble making a calculator. I can't seem to be able to enter the item name, only numbers. Also, it only takes the last price and quantity and multiplies them not the entirety. Update: I made the changes to the code about the subtotal and break,but it keeps telling me
Error CS0029
Cannot implicitly convert type 'string' to 'string[,]'
Error CS0019
Operator '==' cannot be applied to operandstype'string[,]' and 'int'
I can't seem to make it work or add a list to the end. Any help would be appreciated.
int[] array;
string[,] name = new string[100, 4];
decimal counter;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
decimal quantity;
subtotal = 0;
counter = 0;
array = new int[5];
while (counter <= 10)
{
Console.Write("Item{0}", counter + 1);
Console.Write(" Enter item name: ");
name = Console.ReadLine();
if (name == 0)
break;
Console.Write(" Enter price: ");
price = Convert.ToDecimal(Console.ReadLine());
counter = counter + 1;
Console.Write(" Enter quantity: ");
quantity= Convert.ToInt32(Console.ReadLine());
subtotal += price * quantity;
}
Console.WriteLine("-------------------");
Console.WriteLine("\nNumber of Items:{0}", counter);
Console.WriteLine("Subtotal is {0}", subtotal);
tax = subtotal * 0.065M;
Console.WriteLine("Tax is {0}", tax);
total = tax + subtotal;
Console.WriteLine("Total is {0}", total);
Console.WriteLine("Thanks for shopping! Please come again.");
Console.Read();
I also know that I need to have for ( int counter = 0; counter < array.Length; counter++ ) in the code too, but it won't work. Thank-you for your time and help in advance.
You're trying to convert name to a number:
name = Convert.ToInt32(Console.ReadLine());
if (name == 0)
break;
Try removing "Convert.ToInt" like this:
name = Console.ReadLine();
Maybe this program will help you in learning C#. But you have to promise to try to understand how and why it works. Also, use the debugger to step in order to see how each statement affects the values stored in the variables.
class Program
{
static void Main(string[] args)
{
const int max_count = 10;
string[] name = new string[max_count];
int[] quantity = new int[max_count];
decimal[] price = new decimal[max_count];
decimal subtotal = 0;
int count = 0;
// Enter Values
for(int i = 0; i<max_count; i++)
{
Console.Write("Item{0}", i+1);
Console.Write("\tEnter Item Name: ");
name[i]=Console.ReadLine();
if(name[i].Length==0)
{
break;
}
Console.Write("\tEnter Price: ");
price[i]=decimal.Parse(Console.ReadLine());
Console.Write("\tEnter Quantity: ");
quantity[i]=int.Parse(Console.ReadLine());
subtotal+=quantity[i]*price[i];
count+=1;
}
// Display Summary
Console.WriteLine("-------------------");
Console.WriteLine("\nNumber of Items:{0}", count);
Console.WriteLine("Subtotal is {0}", subtotal);
decimal tax=subtotal*0.065M;
Console.WriteLine("Tax is {0}", tax);
decimal total=tax+subtotal;
Console.WriteLine("Total is {0}", total);
Console.WriteLine("Thanks for shopping! Please come again.");
Console.Read();
}
}
What you have here is a structure (the Program) of arrays. There are three arrays each storing a different type of value (string, int ,decimal). Later you should learn to make a single array of a structure, each containing multiple values.
public class Item
{
public string name;
public decimal price;
public int quantity;
}
// Usage
var cart = new List<Item>();
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is for an assignment, please see question and the code i wrote below.
The question:
In the U.S coin system, the penny is the basic coin, and it is equal to cent, a nickel is equivalent to 5 cents, a dime is equivalent to 10 cents, a quarter is equivalent to 25 cents, and half-dollar is equivalent to 50 cents. Design and implement a program that would make use of the functions shown below. Each function has a single int formal parameter Amount.
a) HalfDollars (): Compute the maximum number of half-dollars that could be used in making change for Amount.
b) Quarters():Compute the maximum number of quarter that could be used in making change for Amount
c) Dimes ():Compute the maximum number of dimes that could be used in making change for Amount
d) Nickels () : Compute the maximum number of nickels that could be used in making change for Amount
The code that i wrote:
//Question 1
//please note, i dont have comments everywhere
{
public class MoneyCalc
{
public int Amount;
//a)
public void Half_Dollar()
{
int hd = 2;
int hdOutput = Amount * hd;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + hdOutput);
}
//b)
public void Quater()
{
int q = 4;
int qOutput = Amount * q;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + qOutput);
}
//c)
public void Dimes()
{
int d = 10;
int dOutput = Amount * d;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + dOutput);
}
//d)
public void Nickles()
{
int n = 20;
int nOutput = Amount * n;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + nOutput);
}
}
class Program
{
static void Main(string[] args)
{
//the main program.
//everything is initialised here.
//gets the amount the ser wants to calculate through user input in a string and converts to to an integer.
Console.WriteLine("Please enter an amount to calculate:");
string userAmount = Console.ReadLine();
int amount = Int32.Parse(userAmount);
//users have to make a selection from this list.
Console.WriteLine("");
Console.WriteLine("Please choose what you want to calculate you amount to (Select the number):");
Console.WriteLine("1. Half Dollar");
Console.WriteLine("2. Quater");
Console.WriteLine("3. Dime");
Console.WriteLine("4. Nickel");
//gets the users input(their choice) in a string and coverts it to an integer
string userChoice = Console.ReadLine();
int choice = Int32.Parse(userAmount);
if (choice == 1)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Half_Dollar();
}
else if (choice == 2)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Quater();
}
else if (choice == 3)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Dimes();
}
else if (choice == 4)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Nickles();
}
else
{
Console.WriteLine("Invalid Option");
}
}
}
}
I think, what they looking for is
// amount expected in $$, $2.34
public int GetNumberOfCoins(decimal amount, CoinOption centValue)
{
// you might want to check first if result of truncate is larger than max int value
int numberOfCoins = Convert.ToInt32(Math.Truncate(amount * 100 / (int)centValue));
return numberOfCoins;
}
// And then in your console
public enum CoinOption : int
{
Penny = 1,
Nickel = 5,
Dime = 10,
Quarter = 25,
Half = 50
}
string answer = null;
CoinOption opt;
switch (inputOption)
{
case "1":
opt = CoinOption.Penny;
break;
case "2":
opt = CoinOption.Nickel;
break;
case "3":
opt = CoinOption.Dime;
break;
case "4":
opt = CoinOption.Quarter;
break;
case "5":
opt = CoinOption.Half;
break;
}
// inputAmount originally comes as string but needs to be converted to decimal
answer = GetNumberOfCoins(inputAmount, opt).ToString()
Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}
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
}
}
}
here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.
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();
}