Accepting only decimals and numbers in Console.ReadLine - c#

I have just made a program to calculate the total cost of an item or items given the quantity and price. One of my concerns is in the Cost of Item field, it does not accept decimals at all. I would also like both fields to not accept letters. I have seen something about TryParse but I am unsure of how to use this and how it works. Any help is appreciated.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuantityPrice
{
class Program
{
static void Main(string[] args)
{
int Quantity;
int Cost;
Console.WriteLine("How much is the item you are buying? (In Canadian Dollars)");
Cost = int.Parse(Console.ReadLine());
Console.WriteLine("How many of the item are you buying? (In Canadian Dollars)");
Quantity = int.Parse(Console.ReadLine());
var TotalCost = Quantity * Cost * 1.13;
Console.WriteLine("Your total cost is:");
Console.WriteLine("$" + TotalCost);
Console.ReadLine();
System.Threading.Thread.Sleep(100000);
}
}
}

The problem is you are using int.Parse to extract the values from the user input. The int type is only for integers. If you want to handle decimals, use either float or double (for general mathematics where you want a floating decimal point) or decimal (for fixed point arithmetic such as currency).
As a general style comment, use "camel case" (starting with a lower case character) for variable names instead of "Pascal case" (starting with an upper case character).

You need to use decimals instead of int and to get the value, just ask for it as long as it is not a valid decimal like in this answer Need help with accepting decimals as input in C#
that you could use directly like this:
var cost = RequestDecimal("How much is the item you are buying? (In Canadian Dollars)");
Use an equivalent function to get an int for quantity

Related

C# console app finishing with code 0 instead of providing the output it's supposed to calculate

The program is supposed to calculate compound interest by getting several inputs from the user and then applying those with the compound interest formula, however while gramatically correct, the program does everything correctly except for ouputting the calculated value. Any ideas why this might be happening?
using System;
namespace compoundCalc
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter investment sum:");
int investment = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter annual interest rate:");
double interestRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the number of times per year that interest is compounded per period:");
int compoundNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the number of periods the money is invested for:");
int investmentPeriod = Convert.ToInt32(Console.ReadLine());
double nt = Math.Pow((compoundNumber * investmentPeriod),(1+interestRate / compoundNumber ));
double futureCapital = investment * nt;
Console.WriteLine("The future value of your investment is:", Convert.ToString(futureCapital));
}
}
}
Console.WriteLine(String, Object) method signature requires the string include a format character, which you don't have.
If you want to use String interpolation, then that would look like
Console.WriteLine($"The future value of your investment is: {futureCapital}");
You need to tell the Console where to display the futureCapital add this {0} to last of your string
Console.WriteLine("The future value of your investment is: {0}",Convert.ToString(futureCapital));
or you can use string concatenation +
Console.WriteLine("The future value of your investment is: " + futureCapital);
or more convenient use string interpolation $
Console.WriteLine($"The future value of your investment is:{futureCapital}");

inputting values into an array and printing the total value in the command prompt

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

Assistance with temperature comparisons assignment in C#

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.

System.FormatException error and having issues trying to fix it

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

Check how many instances of strings in a list

Well I enquired about checking if certain keywords can be found in an list and if they are all there the question is correct. Found here: Check if the string contains all inputs on the list
What I would like to also know is how many of the words are in the list, then divide it and get a percentage, so the user knows how accurately they answered each question.
public String KeyWords_Found()
{
int Return_Value = 0;
foreach (String s in KeyWords)
{
if (textBox1.Text.Contains(s))
{
Return_Value++;
}
}
int Holder = Return_Value / KeyWords.Count;
int Fixed = Holder * 100;
return Fixed + "%";
}
So what I want that code it do is check for all instances of keywords listed into the list KeyWords. Then get the percentage by dividing by the total amount of keywords and multiplying by 100. But it says that both values are 0 and i cant divide by 0. I'm not sure why they would be zero. Confused! Help!
You should first check, if KeyWords is empty or not
public String KeyWords_Found()
{
if (KeyWords.Count == 0)
return "0%";
// rest of the code
}
Alternatively you could use Linq instead of writing your own method:
int nOfOccurences = KeyWords.Where(k => textBox1.Text.Contains(k)).Count();
make sure you are using System.Linq; for that to work.
You'll still need to check for KeyWords.Count == 0 and compute the percentage yourself, though.
You should use floating point maths instead of integer maths in your calculations.
int i=100;
int a=51;
(i/a)==0 //true, integer division sucks for calculating percentages
((double)i/a)==0 //false, actually equals ~1.96

Categories

Resources