class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
WriteLine("The area of your circle is: " +
circleArea(Double.Parse(ReadLine())).ToString());
ReadKey();
}
static double circleArea(double radius = 5.00)
{
return Math.PI * (radius * radius);
}
}
I thought I had it set up correctly; however, I receive an error of System.FormatException: 'Input string was not in a correct format. on the line WriteLine("The area of your circle is: " + circleArea(Double.Parse(ReadLine())).ToString()); when no value is entered. I would like it to have a default value of 2. Thanks.
Your problem is that you need to split out the conversion to be able to test for a bad input condition. Take a look at this code.
Console.WriteLine("What is the radius of your circle: ");
var isNumber = Double.TryParse(Console.ReadLine(), out double number);
if (!isNumber)
number = 0;
Console.WriteLine("The area of your circle is: " + circleArea(number).ToString());
Console.ReadKey();
This will test for a legitimate number and if it's not, it just passes zero as the number.
Double.Parse() will always throw a FormatException if the input is not in the form of a valid double.
The behavior of default parameter values is that omitting the parameter when calling the method will cause it to instead use the default value (this is done by inserting the default value into the method call at compile-time). There is no language behavior which would enable an invalid value to be automatically replaced by some default.
In your case, you need to preempt the empty value which is going to Double.Parse(). Something like this:
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
var input = ReadLine();
if (!double.TryParse(input, out var value))
WriteLine($"Invalid input received: {value}");
else
WriteLine("The area of your circle is: " + circleArea(value).ToString());
ReadKey();
}
static double circleArea(double radius = 5.00)
{
return Math.PI * (radius * radius);
}
}
Here's a concise way of testing the input and selecting a default if whatever was input is in an incorrect format.
Console.Write("What is the radius of your circle: ");
var value = double.TryParse(Console.ReadLine(), out var input) ? input : 2d;
Console.WriteLine($"The area of your circle is {circleArea(value)}");
I'd highly advice to do the reading and calculation in two steps
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
var input = ReadLine();
double d = 0.0;
if(!Double.TryParse(input,out d)) {
d = //default value here
}
WriteLine("The area of your circle is: " + circleArea(d).ToString());
ReadKey();
}
}
Related
I am an extreme beginner when it comes to coding, and I am building a batting average calculator as one of my first programs.
Console.WriteLine("Your batting average is: " + (hits / atBats) );
The input for hits is 165 and 419 for atBats, and it calculates to .3937947494. Though this is correct, I would like the number to read as .394. How would I do that?
A sample example that demonstrates usage of Math.Round() function:
using System;
class MainClass {
public static void Main (string[] args) {
double result = 0.3937947494;
Console.WriteLine(Math.Round(result,3));
}
}
// here result is = 0.3937947494, but you will get output as 0.394 in the console.
VERSION 2:
using System;
public class Program
{
public static void Main()
{
int hits = 165;
int atBats = 419;
double result = (double)hits / (double)atBats;
Console.WriteLine("Your batting average is: " +Math.Round(result,3));
}
}
// this produces the same result
// Your batting average is: 0.394
Screenshot for second alternative:
VERSION 3: Serves better readability (as suggested correctly by #Manti_Core
using System;
public class Program
{
public static void Main()
{
double hits = 165;
double atBats = 419;
double result = hits/atBats;
Console.WriteLine("Your batting average is: " + (hits / atBats).ToString("0.000"));
}
}
Hope this helps.
You can use string.Format:
var number = 0.3937947494;
Console.WriteLine(string.Format("{0:0.000}", number));
You can do simple like below :
double hits = 165;
double atBats = 419;
Console.WriteLine("Your batting average is: " + (hits / atBats).ToString("#.000"));
Console.Read();
here your are simply formatting the value that you want to display.
Performance of string format vs boxing values :
String format
Boxing values
I am trying to build a BMI calculator and I the only thing that can be in the main function is method calls. Whenever i run the following code, the calculation answer does not print. How can i fix that?
public static Double EnterWeight(object sender, EventArgs e)
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight(object sender, EventArgs e)
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight(object sender, EventArgs e);
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
Console.WriteLine("Your BMI is: ", BMI);
}
There are some extra lines in the mine that I used for testing.
The result is just a blank
It looks like there are several problems with the code, though they are small. First, you define methods that take in parameters that are not used, like object sender and EventArgs e. You should only define arguments to a method if they are used inside the method, so you can remove those in your case.
Secondly, when you call EnterWeight, you're defining the variables inside the method call, rather than defining them before-hand and then passing them in using the variable names (which would be the way to solve this issue). But since the method doesn't actually require them, they can be removed from the method and therefore removed from the call.
Finally, when writing methods to get strongly-typed input from the user, it is sometimes nice to create a more flexible method that takes in a string used for the "prompt" for the input, and then use the TryParse methods in a loop, which continually loops until they enter valid input. This way you can re-use the same method to get a double from the user and just pass in different prompts.
For example:
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
private static double GetDoubleFromUser(string prompt)
{
double input;
// double.TryParse attempts to convert a string into a double, and
// it returns a bool that indicates success. If it's successful,
// then the out parameter will contain the converted value. Here
// we loop until we get a successful result, then we return the value.
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out input));
return input;
}
public static double GetBMI(double height, double weight)
{
return weight / Math.Pow(height, 2) * 703;
}
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static void Main()
{
string name = GetStringFromUser("Enter your name: ");
double weight = GetDoubleFromUser("Enter your weight in pounds: ");
double height = GetDoubleFromUser("Enter your height in inches: ");
double bmi = GetBMI(height, weight);
Console.WriteLine($"Thank you, {name}. Your BMI is: {bmi}");
GetKeyFromUser("\n\nDone! Press any key to exit...");
}
You are using the Console.WriteLine incorrectly. You need to use {argumentNumber} to indicate what argument to print and where in the string. Considering the following (I had to make some additional adjustments to get your code to compile. However, to answer your direct question, your BMI is not printing out because you are using Console.WriteLine slightly wrong.
public static Double EnterWeight()
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight()
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
//string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight();
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
// Notice the {0}. I tell it where in the string to print the
// argument I passed in out, and the number indicates which argument
// to use. Most of .NET formatting works like this.
Console.WriteLine("Your BMI is: {0}", BMI);
}
And additional strategy is to use the $"" string where you can do the following:
Console.WriteLine($"Your BMI is: {BMI}");
Basically I'm trying to not let the user input string instead of an integer; but on line of code:
else if (Convert.ToString(result) == "")
I get an error.
Full code:
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result = Convert.ToInt32(Console.ReadLine());
if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else if (Convert.ToString(result) == "")
{
Console.Write("Error, you can not convert a text");
}
else
{
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}
The safest way to get a number from a string is to use the TryParse method, because this method returns two values! The actual return type is a bool which indicates whether or not the string was successfully converted, and the other is an out parameter, which is of the type that we're converting to, and which gets set to the converted value (or is set to the default value of the type if the conversion fails).
For temperatures, we often deal with decimal numbers, so a double is probably a good type to store the result. So, we'll use double.TryParse.
Now, since we don't necessarily want to just quit if the user makes a mistake, we should probably do our conversion in a loop, so if it fails, we just ask the user to try again. And since this code will be used in other places as well, we can make a helper method that takes in a prompt that we display to the user, and returns the strongly-typed user response:
private static double GetDoubleFromUser(string prompt = null)
{
double result;
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out result));
return result;
}
With this method, we can now just declare a double and assign it to the return value of the method above, like:
double userInput = GetDoubleFromUser("Enter a temperature: ");
Another thing we can correct in the code are the formulas used to do the conversions. A quick check online shows us that we add a number for kelvin and we do multiplication, division, and addition for Fahrenheit. We can calculate these values on the fly once we have the Celsius temperature from the user:
private static void Main()
{
double celcius = GetDoubleFromUser("Enter a Celcius temperature: ");
double fahrenheit = celcius * 9 / 5 + 32;
double kelvin = celcius + 273.15;
Console.WriteLine("Kelvin = " + kelvin);
Console.WriteLine("Fahrenheit = " + fahrenheit);
GetKeyFromUser("Done! Press any key to exit...");
}
Output
Convert.ToInt32 throws an exception if the input string is not a number. To fix that, you can use int.TryParse instead.
Example:
using System;
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result;
bool isNum=int.TryParse(Console.ReadLine(),out result);
if (!isNum)
{
Console.Write("Error, you can not convert a text");
}
else if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else {
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}
This is literally my first program I've ever written (started learning this past Monday); I am a total newbie.
My question is, how can I prevent exceptions from being thrown when a user enters an invalid character when the program prompts the user for fahreinheit or celsius entry (expecting a number)??? So for example, when a user enters "asfasd", the program throws an exception.
I did a lot of searching on the site before posting this, and I was successfully able to find other input validation questions, however, they were all concerning C and C++ and since I am such a newbie, I have a hard time with understanding those languages and how they relate to C#. Thank you. Please see code:
using System;
namespace Converter
{
class Program
{
static void Main()
{
float? FahrenheitInput = null;
double? CelsiusInput = null;
float? KilogramInput = null;
float? PoundsInput = null;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
FahrenheitInput = float.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
CelsiusInput = double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static float? FahrenheitToCelsius(float? INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double? CelsiusToFahrenheit(double? INPUT)
{
return INPUT * 1.8 + 32;
}
}
}
You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
class Program
{
static void Main(string[] args)
{
double FahrenheitInput = 0;
double CelsiusInput = 0;
double KilogramInput = 0;
double PoundsInput = 0;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static double FahrenheitToCelsius(double INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double CelsiusToFahrenheit(double INPUT)
{
return INPUT * 1.8 + 32;
}
}
TryParse is your good friend here. In most scenarios, you should favor using TryParse than Parse. In your example, you can do something like:
int validInt;
int.TryParse(Console.ReadLine(), out validInt);
float validFloat;
float.TryParse(Console.ReadLine(), out validFloat);
Parse vs. TryParse
The easiest way, IMHO, to change the routine is to rewrite Parse into corresponding TryParse:
// UserChoice = int.Parse(Console.ReadLine());
UserChoice = int.TryParse(Console.ReadLine(), out UserChoice) ? UserChoice : -1;
...
A bit more complex (you have to convert float into float?)
// FahrenheitInput = float.Parse(Console.ReadLine());
float v;
FahrenheitInput = float.TryParse(Console.ReadLine(), out v) ? (float?) v : null;
The same scheme for CelsiusInput
// CelsiusInput = double.Parse(Console.ReadLine());
double d;
CelsiusInput = double.TryParse(Console.ReadLine(), out v) d (double?) d : null;
The underlying mechanic of the code is
We try to parse user input TryParse(Console.ReadLine()...
If parse succeeds (and thus TryParse returns true) we just return the out (parsed value).
If parse fails (and thus TryParse returns false) we return some special a value (-1 for UserChoice or null in case of FahrenheitInput or CelsiusInput)
P.S. in the first switch you have just case 1, case 2 and case 5; however, you've put "This is not a valid entry. Please enter 1, 2, 3, 4, or 5." in the error message. It seems, that you have to either implement case 3 and case 4 in the switch or edit the error message.
Use int.TryParse instead of int.Parse and float.tryParse instead of float.Parse
While all the answers provided seem to work, the question you asked was
how can I prevent exceptions from being thrown [..]
and I just want to point out that you do this by putting the part which throws the exception in an try-catch-block. What this does is it executes the code within try until an exception is beeing thrown and then passes this exceptions as a parameter to the catch-part where you can handle it:
EXAMPLE
do
{
try
{
// the code you already have
}
catch (Exception ex)
{
Console.WriteLine("This is no valid input (" + ex.Message + ")! Try again...");
}
} while (UserChoice != 5);
Of course preventing exceptions from beeing thrown at all in the first place is the better way (as all the other answers do suggest), but this approach works as well and ist more generic in case you run into a similar problem in the future. Using switch-case-statements for error-handling is quite common practice...
Hello guys I am a newbie and I am currently a first year in Computer Science. We have been given an exercise in which we have to convert from Fahrenheit to Celcius with methods (professor advised no static). We have started with C#. Here is my code.
namespace Week3_Exe3._1{
public class Formula
{
public double F;
public double C;
public void calculate(double F, double C)
{
C = (5 / 9) * (F - 32);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
F = double.Parse(Console.ReadLine());
Formula form = new Formula();
Console.WriteLine(F + "Fahrenheit correspond to " + form.calculate() + "Degrees celcius");
}
}
}
I am currently working with Visual Studio Community 2015 and in form.calculate, it reds out the calculate with the error
CS7036 C# There is no argument given that corresponds to the required
formal parameter '' of 'Formula.calculate(double, double)'
I searched for it but I still do not understand what is missing. I created an instance to use, but it's not working. Can anyone give me answer?
Your calculate method expect 2 parameters but you try to call it without parameters. In my humble opinion, it shouldn't take two parameters at all. Just one fahrenheit parameter is enough so it can calculate celsius value.
Also 5 / 9 performs an integer division —it always discards the fractional part— so it will always return 0.
A static method should be enough for your case;
static double Celsius(double f)
{
return 5.0/9.0 * (f - 32);
}
There a few errors in your code. First of all, your function only requires one input parameter, the temperature in Fahrenheit. After you have resolved this, you will find temperature of 100 Fahrenheit will return a temperature of 0 Celcius and this is obviously not correct. You need to modify your equation to use at least one fractional part otherwise C# will implicitly cast the values to integers.
using System;
namespace Week3_Exe3._1
{
public class Formula
{
public double calculate(double F)
{
return (5.0 / 9.0) * (F - 32.0);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
var F = double.Parse(Console.ReadLine());
Formula form = new Formula();
Console.WriteLine(F + " Fahrenheit correspond to " + form.calculate(F) + " Degrees celcius");
}
}
}
Your code has a few holes, my suggested rewrite is this:
public class Formula
{
public double F;
public double C;
public void calculate()
{
C = (5.0 / 9.0) * (F - 32);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
Formula form = new Formula();
form.F = double.Parse(Console.ReadLine());
form.calculate();
Console.WriteLine(F + "Fahrenheit correspond to " + form.C + "Degrees celcius");
}
}
keep in mind that this code only works for F => C, not the other way around.
The right answer is not going to be much use to you unless you understand what parameters and return values are and how to use them.
In your definition of the calculate method
public void calculate(double F, double C)
the method is expecting two input parameters, F and C. This means when you call the method from your main method, you need to pass in two values between the parentheses:
form.calculate(F, C)
As others have pointed out, you really only need one parameter, for the Farenheight. Which brings us to the next bit - how do you get a value back for C? This is what return values are for. That little word in between public and calculate defines the return type for your method. void means nothing is returned. In your case you'll be wanting to return a double. So putting this together the method definition should look like this
public double calculate(double F)
Finally you must actually return the value at the end of your method:
double C = (5.0 / 9.0) * (F - 32);
return C;
As you already assign the value of C you can remove C parameter from your function defenition code. Than your function must be like.
public void calculate(double F)
{
C = (5.0 / 9.0) * (F - 32.0);
}
Than in your code
public class Formula
{
// public double F; remove because F is used as parameter
public double C;
public void calculate(double F)
{
C = (5.0 / 9.0) * (F - 32.0);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
var F = double.Parse(Console.ReadLine()); // Creating new variable
Formula form = new Formula();
form.calculate(F); // Pass parameter to our function
Console.WriteLine(F + "Fahrenheit correspond to " + form.C /* retrive the results of calculation */ + "Degrees celcius");
}
}