Hello I am currently having issues with my project. im currently having issues with my console program where i am taking a users inputs (of which is decimals) and then using them in a if els statements, then finally doing the final math to work out ticket cost.
i have been researching into ways that i could fix this but for the past few hours i haven't been able to find a fix.
i have tried using strings, inter, var and boolen to store the price but when it comes to the final math to work out the cost, only inters do not give me a error.
i think a fix would be to change the way a user chooses the ticket they want but i cannot work out a way of allowing them to pick from the menu of tickets, while having the price values assigned to their input say:
Int family = 39.90
and then using this in some way to asinge the users input a value based on what i state.
Please could anyone suggest a way that i could maybe do this different or a solution to my current division / FormatException error ?
also any other tips on format ect would be much appreciated, all criticism is welcome im trying to learn.
Current console code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace The_Admission_Price_Calculator
{
class Program
{
static void Main(string[] args)
{
Action<string> cw = Console.WriteLine;
cw("Hello welcome to the WildLife park");
cw("We currently have 4 ticket options:");
cw("1: Famliy ticket(2 adults + 3 children) £39.90");
cw("2: Adult ticket £14.90");
cw("3: Child (under 16) £9.90");
cw("4: Senior (over 65) £7.00");
cw("Please input the price of the ticket you would like?");
cw("(EG if you want to child ticket please input 9.90, please also include the decimal place.");
cw("Input your the tickets price you would like to order now please.");
string Answer1;
int TicketCost1;
int TicketAmount1;
int TicketType1;
TicketType1 = Convert.ToInt32(Console.ReadLine());
if (TicketType1 == 39.90)
{
//int Famliy = 3990;
}
else if (TicketType1 == 9.90)
{
//int Child = 990;
}
else if (TicketType1 == 14.90)
{
//int Adult = 1490;
}
else if (TicketType1 == 7.00)
{
//int Senior = 700;
}
else
{
Console.WriteLine("you need to Input from the options, using the price of the ticket, with the decimal included.");
TicketType1 = Convert.ToInt32(Console.ReadLine());
}
cw("your choosen ticket is " + TicketType1 + ", how many tickets of this type would you like?");
TicketAmount1 = int.Parse(Console.ReadLine());
//Rember to Add /100 to the final sum, so that the output is in decimals.
TicketCost1 = TicketAmount1 * TicketType1;
cw("With the choosen amount of tickets of " +TicketAmount1+ " this will cost £" +TicketCost1+" ");
cw("Is this correct? (YES OR NO");
Answer1 = Console.ReadLine();
if (Answer1 == "YES")
{
cw("Tickets are printing now.");
}
if (Answer1 == "NO")
{
cw("Please reselect what tickets you would like");
//code here
}
else
{
cw("You have not entred a vaild asnswer please Input YES Or not in captials");
Answer1 = Console.ReadLine();
//core here
}
Console.ReadKey();
}
}
}
One thing i'd change is to have the user input the number of the option instead of the price when making a selection from the menu which should make things a little easier for you (then the selection is an int)
Like everyone is advising, switch from using int to decimal.
Which affects your conversion from string input too:
//TicketType1 = Convert.ToInt32(Console.ReadLine());
TicketType1 = Convert.ToDecimal(Console.ReadLine());
it also affects the way you do comparisons:
// if (TicketType1 == 39.90)
if (Decimal.Compare(TicketType1,39.90) == 0)
you cannot put decimals into an int. ints hold whole numbers. Traditionally you use double to store fractional things, but this is bad habit for currency. For currency use the decimal type http://csharpindepth.com/Articles/General/Decimal.aspx
Related
I am confused. When I write the following code, and start the program up, it just shows a blank output. I read online what the problem could be and the most people seem to agree that it's a problem in my code after all, but I cant see where I messed up:
sorry forgot to put the details guys. This is the assignment and the different input/outputs etc:
You and your colleagues are huge fans of your local football team. You therefore often show up to support your team. When your team has made at least ten perfect passes to each other, you give each other one "high five" and "cheers". At more than one and up to ten passes, cheer in "huh!" for each delivery. If your team scores a goal break out in "Olé olé olé". If you have zero submissions, you are silent and say "Shhh". Your boss is so excited about the way you support your team. Therefore you will be tasked to make a program that can run your logic, so that other colleagues can join next time there is local showdown.
TASK
Based on the number of passes played, which your local team has managed, the following applies:
• "High Five - Cheers!!!" for 10 submissions and above,
• "Shh" for less than 1 delivery
• or a string that has "Huh!" for each pass played.
• If your dream team scores a goal, print ONLY "Olé olé olé".
Requirements for Input
The program takes two inputs, an int and string value. The first value represents number submissions and the next value takes the text "target" as input value.
Targets must be able to be written in CAPITAL or lowercase letters, or in one or more capital and small letters letters.
Output
A string that suits your cheering level
Ex 1 on input
5
Goal
Ex 1 on output
Olé olé olé
Ex 2 on input
3
string.Empty;
Ex 2 on output
Huh! Huh! Huh!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProjectFodbold
{
internal class Program
{
static void Main(string[] args)
{
int i = 1;
int Passes = Convert.ToInt32(Console.ReadLine());
string GoalCheck = Console.ReadLine();
string Goal = "Goal";
string Output1;
if (Goal.Equals(GoalCheck, StringComparison.OrdinalIgnoreCase) == true)
{
Console.WriteLine("Olé olé olé");
}
else if (Passes == 0)
{
Console.WriteLine("Shhh.");
}
else if (Passes > 9)
{
Console.WriteLine("High Five - Cheers!!!");
}
else
{
Output1 = "Huh! ";
while (i < Passes)
{
Output1 = Output1 + "Huh! ";
i = i + 1;
}
Console.ReadLine();
}
}
}
}
Hope someone can give me some insight on this problem
I have tried looking for the problem but no luck
The implementation is not very solid, but i can see you are in the learning phase, so here there are some comments:
I would strongly recommend avoiding Convert without having a try catch because it can generate an exception if the input is not correct, so i would do something like this:
bool isInputValid = int.TryParse(Console.ReadLine(), out int Passes);
And after that it would be great if you validate the inputs from your user, using some extra logic.
The problem with your implementation is that it is not clear what is required, so i suggest to write to the console some help messages:
Console.WriteLine("Insert number of Passes");
bool isInputValid = int.TryParse(Console.ReadLine(), out int Passes);
Console.WriteLine("Write goal Check");
string GoalCheck = Console.ReadLine();
And delete the Console.ReadLine() after your While loop, instead just write it in the last line of your code.
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}
I am trying to create an array that holds prices that the user inputs into the command prompt.
This is what I have so far
using System;
using static System.Console;
namespace Chapter6._2
{
class Program
{
static void Main()
{
int price;
int[] pricesList = new int[9];
Write("Enter price 1: ");
price = Read();
}
}
}
Also how would I create a loop to where it asks for the price of an item 10 times but goes something like this...
"Enter price 1: < user input price >"
"Enter price 2: < user input price >"
"Enter price 3: < user input price >"
and etc...Hopefully that makes sense.
Basically with these 2 questions I have asked, how would I create a loop where the program asks the user for prices 10 times, and stores the prices in an array and prints the total of all of the prices entered into the program at the end.
You need to use a for loop, cycling many times as your array length. Each iteration will ask the user for the Nth price, store it in the Nth position of the array and add the price to some "sum" variable. Also maybe you want to check System.Convert class.
This is as far I can go without doing your homework for you.
Please read this before asking more school related stuff:
How do I ask and answer homework questions?
Think of using a for loop. Your condition should be like i <= pricesList.Length
You can ask for user input as something like this: Console.WriteLine("Enter price {0}", i); or Console.WriteLine("Enter price {0}", i+1); if you want to start with 1 and not 0.
See array loops here C# arrays
I'm kinda new to C#, and I'm currently doing an assignment which is having me do three things:
1) Write a program named TemperaturesComparison that allows a user to input five daily Fahrenheit temperatures that must range from −30 to 130.
2) Display the temperatures in the order they were entered, and then display the average of the temperatures.
3) If a temperature is out of range, require the user to reenter it. If no temperature is lower than any previous one, display a message Getting warmer. If every temperature is lower than the previous one, display a message Getting cooler. If the temperatures are not entered in either ascending or descending order, display a message It’s a mixed bag.
The first two I've basically already got, but I'm not 100% sure how to address the third one in the most convenient way. Any advice on how to best handle this one would be greatly appreciated!
Here's a sample of the code I've written so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
class TemperaturesComparison {
static void Main(string[] args) {
string userInput;
// Set Array Range
const int ARRAY_RANGE = 5;
const double AVG_RANGE = 5.0;
int[] dblArray = new int[ARRAY_RANGE];
int total = 0;
double average = 0;
WriteLine("This application calculates the average temperature of a provided dataset.\n");
for (int i = 0; i < ARRAY_RANGE; ++i) {
do {
Write("\nPlease provide temperature {0}: ", i + 1);
userInput = ReadLine();
} while (!int.TryParse(userInput, out dblArray[i]));
}
for (int i = 0; i < ARRAY_RANGE; ++i) {
total += dblArray[i];
}
foreach(var numListHolding in dblArray)
Write(numListHolding.ToString() + " ");
average = total / AVG_RANGE;
Write("\nAverage: {0}", average);
ReadKey();
}
}
You're making a few common beginner mistakes. First, arrays are better for collections that have a fixed size and never change, like the months of a year. If you want to have a changing number of entries, use something like a list:
var temperatures = new List<float>();
Second, integers are a poor type for real-world measurements like temperature. Prefer a floating-point type like float or double.
Next, variable names should tell you what the variables contain; names like userInput don't tell us that.
Next, your code doesn't “allow” a user to input five temperatures, it requires them to enter exactly five and will throw exceptions if they don't. Design your loops to work with any number of inputs:
while (true)
{
var nextTemperature = GetTemperatureFromSomewhere();
if (nextTemperature == null)
break;
if (nextTemperature is valid)
temperatures.Add(nextTemperature);
}
Look at the code above. If nextTemperature is not null but out of range you don't want to add it to temperatures.
When you have that working you want to store a maximumTemperature and compare it to each nextTemperature. If every nextTemperature exceeds maximumTemperature then your temperatures are getting warmer.
I am creating a simple income tax calculator and would like too add some user input validations. Currently I am experimenting with a TryParse method. I would like my program to check each input for the specific input types and if an invalid input is entered, the program will first notify the user then ask them to try again.
My current attempt successfully detects whether or not the input types are correct, but I am unsure on how I can redirect the user to retry. Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IncomeTaxCalculator
{
class IncomeTaxV2
{
public static void Main()
{
// Define variables
const double incomeTax = 0.02, deduction = 10000; // Constant values - These never change
int children; // Amount of children
double Taxdue, totalIncomeTax; // Decimal valued variables
// Ask total income
Console.Write("What is your total income: ");
bool succeed = double.TryParse(Console.ReadLine(), out totalIncomeTax);
// Ask amount of children
Console.Write("How many children do you have: ");
bool succeeded = int.TryParse(Console.ReadLine(), out children);
// If statement to check input validation.
if (succeed && succeeded)
{
// User input validation
// Calculate Deductions
int childTax = children * 2000; // total amount for each child
double total_deductions = (double)deduction + childTax; // total deductions = 10k + childtax
// Calculate User input tax takeaway (-) the total amount of deductions (Equation above)
double taxDueCalc = totalIncomeTax - total_deductions;
// Find 2% of the Result for the amount of Tax due
Taxdue = taxDueCalc * incomeTax;
// Print result
Console.Write("You owe a total of $" + Taxdue + " tax.");
} else
{
// Notify user of error
Console.Write("You must enter a valid number.");
// Redirect too first set of TryParse statements
}
// End program
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
}
}
Redirect must go into else statement. After researching potential methods it seems I might have too learn too use functions and pass information through parameters.
An easy approach is to use a loop, and signal the end when user entry has completed:
bool entryCompleted = false;
while (!entryCompleted)
{
if (succeed && succeeded)
{
// ..
entryCompleted = true;
}
}
I will use the recursive function for this question.
public static void Main()
{
incomeTax();
// End program
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
public void incomeTax()
{
// Define variables
const double incomeTax = 0.02, deduction = 10000; // Constant values - These never change
int children; // Amount of children
double Taxdue, totalIncomeTax; // Decimal valued variables
// Ask total income
Console.Write("What is your total income: ");
bool succeed = double.TryParse(Console.ReadLine(), out totalIncomeTax);
// Ask amount of children
Console.Write("How many children do you have: ");
bool succeeded = int.TryParse(Console.ReadLine(), out children);
// If statement to check input validation.
if (succeed && succeeded)
{
// User input validation
// Calculate Deductions
int childTax = children * 2000; // total amount for each child
double total_deductions = (double)deduction + childTax; // total deductions = 10k + childtax
// Calculate User input tax takeaway (-) the total amount of deductions (Equation above)
double taxDueCalc = totalIncomeTax - total_deductions;
// Find 2% of the Result for the amount of Tax due
Taxdue = taxDueCalc * incomeTax;
// Print result
Console.Write("You owe a total of $" + Taxdue + " tax.");
} else {
// Notify user of error
Console.Write("You must enter a valid number.");
// Redirect too first set of TryParse statements
incomeTax();
}
}
When the input number is invalid, it will call back the same function. This happens until the program enters if statement.