Im having problem with a program that takes farenheight translates it to celsius and tells you if the temperature is too low or too high.
Right now the to low part works but for some reason the loop doesn't work when it's to high.
using System;
namespace Bastun2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter temperature");
double temperatureF = double.NaN;
if (double.TryParse(Console.ReadLine(), out temperatureF) && temperatureF < 163.4)
{
Console.WriteLine($"{temperatureF}°F is to low, enter a higher temperature");
}
//double temperatureC = (temperatureF - 32) * 5 / 9;
//Console.WriteLine($"{temperatureF}°F, {temperatureC}°C");
else if (double.TryParse(Console.ReadLine(), out temperatureF) && temperatureF > 170.6)
{
Console.WriteLine($"{temperatureF} °F is to high, enter a lower temperature");
}
double temperatureC = (temperatureF - 32) * 5 / 9;
Console.WriteLine($"{temperatureF}°F, {temperatureC}°C");
}
}
}
You don't have any loop here.
Store the result of Console.ReadLine() in a variable like so :
double temperatureF = double.NaN;
double.TryParse(Console.ReadLine(), out temperatureF);
And replace where you used Console.ReadLine() previously by temperatureF.
You are reading two times from the console. After your first check failed, the user has to input another value so the second check can happen.
You should only read the input once and store it in a varibale. Then you can check on that variable.
You could also use a loop, so the user does not have too restart the program until he enters a valid input.
static void Main(string[] args)
{
double temperatureF = double.NaN;
string input = string.Empty;
bool inputIsOkay = false;
while(!inputIsOkay)
{
Console.WriteLine("Enter temperature");
input = Console.ReadLine();
if (!double.TryParse(input, out temperatureF))
{
Console.WriteLine($"'{input}' is not a valid input...");
}
else if (temperatureF < 163.4)
{
Console.WriteLine($"{temperatureF}°F is to low, enter a higher temperature");
}
else if (temperatureF > 170.6)
{
Console.WriteLine($"{temperatureF} °F is to high, enter a lower temperature");
}
else
{
inputIsOkay = true;
}
}
double temperatureC = (temperatureF - 32) * 5 / 9;
Console.WriteLine($"{temperatureF}°F, {temperatureC}°C");
Console.ReadKey();
}
Related
I would like for someone to help me by telling me what code I should use in case the input number turns out to be for the second if or third if, if the user doesn't put the right amount (73-77) then id like the user to be able to type in a new value I can use... how do I do that please?
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
Console.WriteLine("write down temprature: ");
int fahrenheit = int.Parse(Console.ReadLine());
int celsius = FahrToCels(fahrenheit);
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
do
if (celsius >= 73 && celsius <= 77)
{
Console.WriteLine("now it works ");
}
else if (celsius < 72)
{
Console.WriteLine("");
}
else if (celsius > 77)
{
Console.WriteLine("");
}
while (true);
}
}
}
There are a few major issues with what you have. Attached is working code for what I believe you are looking for, though in your ifs you have Celsius range in the 70s when the point of your Fahrenheit to Celsius converter turns the value into Celsius which would lie in the 20s range.
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
int celsius;
int fahrenheit;
do
{
Console.WriteLine("Skrive in Temperaturen: ");
fahrenheit = int.Parse(Console.ReadLine());
celsius = FahrToCels(fahrenheit);
Console.Write("Presifs any key to continue . . .");
Console.ReadKey(true);
if (celsius >= 22 && celsius <= 28)
{
Console.WriteLine("now it works ");
//Insert whatever here
break;
}
else if (celsius < 22)
{
//Something to tell them they need to retry
}
else if (celsius > 28)
{
//Something to tell them they need to retry
}
}
while (celsius >= 22 && celsius <= 28);
}
}
}
I would recommend changing the range on your ifs to the values you want the user to input, and also provide the user with some error/retry statement in your elseifs. Also would recommend instead of having two elseifs just use else. Also would remove that stupid readkey() in my opinion.
If you have any questions to my answer leave them in the comments.
If you want to ensure that celsius is in [73..77] range you can try
static void Main(string[] args) {
int fahrenheit;
int celsius;
// Keep asking user until (s)he enters a valid celsius value
while (true) {
Console.WriteLine("Skrive in Temperaturen: ");
// check if value a valid integer, and not say "bla-bla-bla"
if (!int.TryParse(Console.ReadLine(), out fahrenheit)) {
Console.WriteLine("Not an integer value, please, try again");
continue;
}
// fahrenheit is a valid integer value, we can compute corresponding celsius...
celsius = FahrToCels(fahrenheit);
// ... and validate the celsius value then
if (celsius < 73)
Console.WriteLine("Too low temperature (below 73 degree Celsius)");
else if (celsius > 77)
Console.WriteLine("Too high temperature (above 77 degree Celsius)");
else
break; // celsius is valid integer value in [73..77] range
}
// From now on celsius contains integer in [73..77] range
Console.WriteLine("Now it works");
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
}
Is there any way for me to clean this code up for it to be more efficient? Also, could someone point me into the direction of making this app more advanced than what I have done?
As I am progressing with C# and starting to understand more about what certain things do I am lost as to how to implement my knowledge into actual code.
Any starting points for creating applications to help me remember how to and when to use certain code, for example: Encapsulation, interface polymorphism etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNetCalculator
{public class Calculator
{
// User Input1
public int number1;
// User Input2
public int number2;
// User Input3
public int number3;
//User Input4
public char YesOrNo;
// Input1 property
public int Input1 { get
{
return number1;
} set {
number1 = value;
}
}
// Input2 property
public int Input2 { get
{
return number2;
} set {
number2 = value;
}
}
// Input3 property
public int Input3
{
get
{
return number3;
}
set {
number3 = value;
}
}
// Input4 property
public char Input4
{
get
{
return YesOrNo;
}
set
{
YesOrNo = value;
}
}
//Addition
public void Addition(int number1, int number2)
{
Console.WriteLine("\nAddition of the 2 Numbers is " + (number1 + number2));
}
//Subtraction
public void Subtraction(int number1, int number2)
{
Console.WriteLine("Subtraction of the 2 Numbers is: " + (number1 - number2));
}
//Division
public void Division(int number1, int number2)
{
Console.WriteLine("Division of the 2 Numbers is: " + (number1 / number2));
}
//Multiplication
public void Multiplication(int number1, int number2)
{
Console.WriteLine("Multiplication of the 2 Numbers is: " + (number1 * number2));
}
}
class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator();
//Start of the application
Start:
Console.WriteLine("\nCalculation of the 2 numbers using 4 different operations");
//User input with the first number
Console.Write("\nEnter The first number: ");
calc.Input1 = Convert.ToInt16(Console.ReadLine());
//User input with the second number
Console.Write("Enter the second number: ");
calc.Input2 = Convert.ToInt16(Console.ReadLine());
//User input which is equal to 1 of the 4 math operations
Console.Write("Press 1 for Addition, Press 2 for Subtraction, Press 3 for Division or Press 4 for Multiplication: ");
calc.number3 = Convert.ToInt16(Console.ReadLine());
// if the user input is 1 then call the addition operation
if (calc.number3 == 1)
{
//call addition
calc.Addition(calc.number1, calc.number2);
}
else
// if the user input is 2 then call the subtraction operation
if (calc.number3 == 2)
{
//call subtraction
calc.Subtraction(calc.number1, calc.number2);
}
else
// if the user input is 3 then call the division operation
if (calc.number3 == 3)
{
//call division
calc.Division(calc.number1, calc.number2);
}
else
// if the user input is 4 then call the multiplication operation
if (calc.number3 == 4)
{
//call multiplication
calc.Multiplication(calc.number1, calc.number2);
}
//User input for starting again or finishing the application
Console.Write("\nWould you like to start again? Y or N: ");
calc.YesOrNo = Convert.ToChar(Console.ReadLine());
//if the user input is equal to Y then send them back to the start of the application
if (calc.YesOrNo == 'Y')
{
goto Start;
}
else
// if the user input is equal to N then send them to the end of the application
if (calc.YesOrNo == 'N')
{
goto End;
}
//End of the application
End:
//Exit
Console.WriteLine("\nPress Enter to exit!");
Console.Read();
}
}
}
My comments:
In your Calculator class, you should not put variable that are not useful for the class like number3.
No reason to have both a public variable and a property.
No reason to use goto in a program like that. Prefer while loop.
Find better name for your variables.
You main function should be split in multiple small functions.
Use enum for operations.
Be consistent with your types. Given that the calculator accept 32 bit inputs, you should probably convert user input to 32 bit integers.
Formatting could be improved
And more...
I am trying to continuously ask user for a number between 300-850. When the user enters a valid number, add it to the total and ask again. If the number is invalid, display an error. Before program ends, display the average of total number by amount of times of input. End program if user enters a sentinel value. I don't know how to check if user enters a sentinel value.
using System;
class CreditScores
{
static void Main()
{
var iterations = 0;
double total = 0;
int sum = 0;
double average = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentinel value reached.
while (iterations < 1000)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
int input = int.Parse(Console.ReadLine());
//not sure how to check if input is a number or not
if(input == integer)
{
if( input < 850 && input > 300 )
{
total +=input;
}
}
else
{
break;
}
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
average = total / count;
Console.WriteLine("The average is {0}", average);
}
}
Modification/fix of Your Method
Also, I would read all the way to the end for the more robust method you could use.
First thing I would change:
while (iterations < 1000)
{
...
}
To this (which we are not done yet, read to the end):
while (input != "calculate") // or some other string
{
...
}
Then, before the while starts, make input a string.
string input = "";
while (input != "calculate") // or some other string
{
...
}
Now, we declared an input variable that is already an int later on. Let's fix that.
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Now, we need to put it together and do some cleaning.
int total = 0;
int numbersEntered = 0;
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
numbersEntered++;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
}
Console.WriteLine("Total is {0}", total);
double average = (double)total / numbersEntered;
Console.WriteLine("The average is {0}", average);
(I know, long answer. But it should help you step through the problem in the future. Also, I wrote this all by memory, I can't guarantee it will compile.)
Update: just tested it, works as expected.
A more Robust Method
Lastly, and this is really the coolest method in my opinion, use a List<int> and some extension methods.
List<int> values = new List<int>();
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
values.Add(value);
else
{
// Was outside our range
}
else
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Console.WriteLine("Total is {0}", values.Sum());
Console.WriteLine("The average is {0}", values.Average());
Advantages to this method? It saves a list of the values entered, allowing you to do more with them that you cannot do with the method you currently have. It also uses the int.Sum() and int.Average() extension methods rather than your own math.
What is this int.TryParse(string, out int) sorcery?
The int.TryParse(string, out int) method (as defined by MSDN) will take an input string, and return a boolean value that indicates if it would make a valid int structure or not.
In the case that the string is a valid int, then the int parameter is filled with the integer representation of the string.
I.e.:
string myString = "100";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return true and print: myString was a valid int: 100.
Example 2:
string myString = "blah";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return false, and print myString was not a valid int.. The value variable would also be 0.
Warning:
When using int.TryParse(string input, out int value), do not rely on the value parameter as 0 to indicate failure. If the input is "0", then the value will also be 0, and the method will return true.
You want to set the condition of your while loop to something that a user can trigger as false (the sentinel).
Then put a for loop inside that if you want to do a set number of iterations, for loops are better for situations where you know how many iterations you're doing.
BUT if you want to stick to while loops only, here's a quick code snippet you could use:
while (input != 0 && iterations < 1000) //or some sentinel value you choose
{
//Your logic here, now the loop will quit if if the user enters 0
//OR you run out of iterations
}
using System;
class CreditScores
{
static void Main()
{
double total = 0;
int sum = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentihel value reached.
for (iterations = 0; iterations < 1000; iterations++)
{
Console.WriteLine("Enter value between 300 to 850.");
int input;
// Check number is integer
if (int.TryParse(Console.ReadLine(), out input)
{
if(input > 300 && input < 850)
{
total +=input;
}
}
else
{
break;
}
count++;
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
double average = total/count;
Console.WriteLine("The average is {0}", average);
Console.ReadLine(); // Either this or run with Ctrl-F5
}
}
The behaviour would be to add the totals until the user entered something that couldn't be parsed, and then exit.
Does this work?
string sentinalValue = "done";
string input = "";
while (iterations < 1000 && input != sentinalValue)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if( value < 850 && value > 300 )
{
total +=input;
}
}
else
{
Console.WriteLine("That is not a number!");
}
}
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.
The program I've written is set to only accept positive integers as input. If the user inputs a letter instead, then it crashes. Negative integers don't cause any problems, though it's not 'valid' in regards to how my program functions.
What I want to do is:
Prevent the program from crashing from invalid input.
Display an error message if the input is invalid
Have the program continue where it left off, without affecting the rest of the program.
Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?
This is in C#
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue;
do
{
Console.WriteLine("Enter Striking Level: ");
string striking = Console.ReadLine();
Console.WriteLine("Enter Grappling Level: ");
string grappling = Console.ReadLine();
Console.WriteLine("Enter Submission Level: ");
string submission = Console.ReadLine();
Console.WriteLine("Enter Durability Level: ");
string durability = Console.ReadLine();
Console.WriteLine("Enter Technical Level: ");
string technical = Console.ReadLine();
Console.WriteLine("Enter Speed Level: ");
string speed = Console.ReadLine();
Console.WriteLine("Enter Hardcore Level: ");
string hardcore = Console.ReadLine();
Console.WriteLine("Enter Charisma Level: ");
string charisma = Console.ReadLine();
int gra = Convert.ToInt32(grappling);
int str = Convert.ToInt32(striking);
int dur = Convert.ToInt32(durability);
int spd = Convert.ToInt32(speed);
int tec = Convert.ToInt32(technical);
int hdc = Convert.ToInt32(hardcore);
int cha = Convert.ToInt32(charisma);
int sub = Convert.ToInt32(submission);
int total = str + gra + sub + dur + tec + spd + cha + hdc;
int overall = total / 8 + 8;
Console.WriteLine("The Overall is " + overall);
Console.WriteLine("Do you wish to continue? y/n? ");
if (Console.ReadLine() == "y")
{
shouldContinue = true;
}
else break;
} while (shouldContinue == true);
}
}
}
int value = 0;
if (!int.TryParse(input, out value))
{
MessageBox.Show("Oops");
} else {
// use the value in the variable "value".
}
static void Main(string[] args)
{
bool validInput = false;
string inputString;
UInt32 validPositiveInteger = 0;
while (!validInput)
{
Console.WriteLine("Please enter a positive 32 bit integer:");
inputString = Console.ReadLine();
if (!UInt32.TryParse(inputString, out validPositiveInteger))
{
Console.WriteLine("Input was not a positive integer.");
}
else if (validPositiveInteger.Equals(0))
{
Console.WriteLine("You cannot enter zero.");
}
else
{
validInput = true;
//Or you could just break
//break;
}
}
Console.WriteLine(String.Format("Positive integer = {0}", validPositiveInteger));
}
Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue = true;
while (shouldContinue)
{
int strikingLevel = GetValue("Enter Striking Level: ");
int grapplingLevel = GetValue("Enter Grappling Level: ");
int submissionLevel = GetValue("Enter Submission Level: ");
int durabilityLevel = GetValue("Enter Durability Level: ");
int technicalLevel = GetValue("Enter Technical Level: ");
int speedLevel = GetValue("Enter Speed Level: ");
int hardcoreLevel = GetValue("Enter Hardcore Level: ");
int charismaLevel = GetValue("Enter Charisma Level: ");
int total = strikingLevel + grapplingLevel + durabilityLevel + submissionLevel +
technicalLevel + speedLevel + charismaLevel + hardcoreLevel;
int overall = total / 8 + 8;
Console.WriteLine("\nThe Overall is {0}.", overall);
while (true)
{
Console.WriteLine("Do you wish to continue? y/n? ");
string response = Console.ReadLine();
if (response.Equals("y", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = true;
break;
}
else if (response.Equals("n", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = false;
break;
}
}
}
}
private static int GetValue(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
string input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if (value <= 0)
Console.WriteLine("Please enter a positive number.");
else
return value;
}
else
{
Console.WriteLine("Please enter a number.");
}
}
}
}
}
Yes... before you do anything calculations, you need to validate the data you are going to use. If any data is incorrect, then you display a messagebox detailing the errors and return focus to the form so the user can fix the errors. Repeat as necessary.
I wrote this one many moons ago when I first learned C#. It is a conversion from a VB function that I got back in VB5 days. The major benefit of the function is that there is no error - an input will just not allow any characters outside of the predefined list.
/***********************************************************************
* bool ValiText(char inChar,
* string valid,
* bool editable,
* bool casesensitive
* Description: Validate Input Characters As They Are Input
* Notes: For each control whose input you wish to validate, just put
* e.Handled = ValiText(e.KeyChar, "0123456789/-" [,true][,true])
* In The KeyPress Event
***********************************************************************/
public bool ValiText(char inChar, string valid, bool editable, bool casesensitive)
{
string inVal = inChar.ToString();
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
/// Case InSensitive - Make Them Both The Same Case
if (!casesensitive)
{
tst = tst.ToLower();
inVal = inVal.ToLower();
}
return tst.IndexOf(inVal,0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid, bool editable)
{
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
return tst.IndexOf(inChar.ToString(),0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid)
{
return valid.IndexOf(inChar.ToString(),0,valid.Length) < 0;
}
Note That This Will Not Work On A Web APP.