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);
}
}
}
Related
Hello i'm trying to create a calculator game but it loops only 2 times and (idk why)not til the user finds the result with input. And i'll later see how to make a random generator of numbers instead of writing them by myself in the code. Ty for helping.
Yassine
using System;
namespace G
{
class Program
{
static void Main(string[] args)
{
Calcul(2, 2);
}
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
Console.WriteLine("Combien font " + nombre1 + " + " + nombre2);
int supposed = int.Parse(Console.ReadLine());
if(result != supposed)
{
Console.WriteLine("Try again!");
supposed = int.Parse(Console.ReadLine());
}
else
{
Console.Clear();
Console.WriteLine("Correct!");
}
}
}
}
You can change your if statement to a while loop whose condition is that the input does not match the result. We can also use int.TryParse with Console.ReadLine to handle cases where the user doesn't enter a valid number. This works by taking an out parameter that gets set to the parsed value if it's successful, and it returns a bool that indicates success. Perfect for a loop condition!
Then you can put the "success" message after the body of the while loop (because the only way to exit the loop is to get the correct answer). It would look something like:
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
int input;
Console.Write($"Combien font {nombre1} + {nombre2} = ");
while (!int.TryParse(Console.ReadLine(), out input) || input != result)
{
Console.WriteLine("Incorrect, please try again.");
Console.Write($"Combien font {nombre1} + {nombre2} = ");
}
Console.WriteLine("Correct! Press any key to exit.");
Console.ReadKey();
}
So i am trying to return the discount amount between 2 .cs files into the main and print out the amount there instead of doing it on the second class. I am pretty new at this and i need help
code is not yet complete
MAIN
using System;
namespace CalcDiscount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter price");
double input = double.Parse(Console.ReadLine());
Calculator myCalculator = new Calculator();
myCalculator.Calculation(input);
Console.WriteLine("Enter discount");
input = double.Parse(Console.ReadLine());
Console.WriteLine("");
Console.ReadLine();
}
}
}
SECOND FILE
calculator.cs
using System;
namespace CalcDiscount
{
public class Calculator
{
public void Calculation(double input)
{
Console.WriteLine("Your entered the number: " + input);
int i = 1;
if (input != 0)
{
Console.WriteLine(input + " x " + i + " = " + input * i);
}
}
}
}
You could change the method Calculation in your Calculator class, from void to double. The method will calculate the result and return it to the main function, where it will be printed.
Calculation method:
public double Calculation(double input1, double input2)
{
return (input1 * input2);
}
Main:
Console.WriteLine("Enter first input");
double input1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second input");
double input2 = double.Parse(Console.ReadLine());
Calculator myCalculator = new Calculator();
double result = myCalculator.Calculation(input1, input2);
Console.WriteLine("result = " + result);
public class Calculator
{
public double Calculation(double input)
{
Console.WriteLine("Your entered the number: " + input);
int i = 1;
double result = 0;
if (input != 0)
{
result = i * input;
}
return result;
}
}
I made here a few changes
changed the return type to double (because you send double so it logical to return the same type but not necessary
add a result variable to return the result
did the calculation ( result = i * input)
return the result
note that if i == 0 the result will be 0, because result is initialized to zero, but can apply any logic that you want
and in your Main i read the result from the function and output it to the Console
double result = myCalculator.Calculation(input);
Console.WriteLine("caculcation result is" + result);
I have public string method with an if/else statement. When I don't put a return keyword on the else, I get the error that not all code paths return a value but when I add the return to the else statement, I get an Use of unassigned local variable 'result'. When I do return "Please enter a valid number";, nothing displays on the console when I type in any letter. I need to let the user know that they entered something in that couldn't be converted into an integer.
public string AddNumbers(string userInputString)
{
int result;
int num2 = RandomNumberInt();
bool isTrue = int.TryParse(userInputString, out int num1);
if (isTrue == true)
{
result = num1 + num2;
Console.WriteLine("Adding your number and a random number, please wait...");
Thread.Sleep(1000);
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
isTrue = true;
return result.ToString();
}
else
{
return "Please enter a valid number";
}
}
It's because your method is asking for a return. But since you have an if, let's put it this way
Team Leader: Hey bob I want you to finish this job.
In here you are expecting that bob will finish your job but you put a condition
You: If I can go to office today sir.
since you have an If condition, what if you can't go today? Does it mean you can't finish the job tomorrow and any other day? That's why it says not all code paths return a value because you never gave other/default value
Going back in your code, you ask
if (isTrue == true)
{
result = num1 + num2;
Console.WriteLine("Adding your number and a random number, please wait...");
Thread.Sleep(1000);
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
isTrue = true;
return result.ToString();
}
but what if it is not true, then it will go to else. You can set int result = 0 so it is defined from start when else run and it will not return an error of unassigned local variable.
public string myMethod()
{
int result = 0; //This must have a default value so in else part it is not unassigned when you return.
int num2 = RandomNumberInt();
bool isTrue = int.TryParse(userInputString, out int num1);
if(isTrue)
{
//do something in result here
return result.toString(); //This will return your in value as string
}
else
{
return "Your message as string" // This will return any string to provide for string return of the method
}
}
Your problem regarding not displaying the string "Please enter a valid number" is a different issue. You have to post also what method calls the AddNumbers method that will use the returned string. For use the problem is in that method because your if and else is in correct format;
Whenever you get confused by application logic, it is often helpful to break the logic down into pieces. This gives you an opportunity to think through the problem and decide how the tasks add up to give you the final result.
Start at a high level and sketch out the overall flow:
static public void MethodNameThatDescribesThisActivity()
{
var userResponse = ReadIntegerFromConsole("Please enter an integer.");
var randomNumber = RandomNumberInt();
DisplaySum(userResponse, randomNumber, 1000);
}
Then implement the pieces:
static public int ReadIntegerFromConsole(string prompt)
{
int result;
while (true)
{
Console.WriteLine(prompt);
var input = Console.ReadLine();
var ok = int.TryParse(input, out result);
if (ok) break;
Console.WriteLine("That isn't a valid integer.");
}
return result;
}
static public void DisplaySum(int userNumber, int randomNumber, int delay)
{
var sum = userNumber + randomNumber;
Thread.Sleep(delay);
Console.WriteLine("The total of {0} + {1} = {2}", userNumber, randomNumber, sum);
}
If you do it this way, it often solves the logic problem for you. And it also makes your code easier to read.
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...
So line #59 has what i can only describe as a wackadoodle error (if i'm understanding my code correctly that is) which is that if you leave the return line with Console.ReadLine() the file will run, if you change it to Console.Read()), the file will produce errors when running. The odd thing is that it shouldn't run because I don't call the functions or do the actual console.writes, etc. So i was hoping someone out there could help me to understand this and either confirm that i am correct in thinking i've got some wacky code OR that my understanding of how the code runs is incorrect.
Code that produces the error:
public string GetStr(String StrVar)//note - using strings here
{
Console.Write(StrVar);return Console.ReadLine().ToLower().Trim();
}
If the line return Console.ReadLine() is changed to return Console.Read(), the file errors - but the file should really run regardless as i don't actually call anything - it seems like the string vars are somehow self-writing to the console if i understand what is happening.
Full Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace a015_mealCalculator
{
class Program
{
public void Play()
{
//DisplayChek("DisplayChek!");
do //do while loop
{
DisplayStr(">>>-- Meal Calculator v1.3 --<<< \n\n\n");//Welcome
//ask info
String fName = GetStr("Enter your FIRST NAME here: ");
String lName = GetStr("Enter your LAST NAME here: ");
String rName = GetStr("Enter the NAME of the RESTURANT you are dinning at here: ");
String wholeName = fName + " " + lName;
double mealCost = GetDouble("How much was your meal " + fName + "?");
String mealGreeting = "\n" + wholeName + ", your meal at " + rName + " was:";
//process math
double tax = mealCost / 8;
double tip = mealCost % 18;
double totalCost = mealCost + tip + tax;
tax = Math.Round(tax, 2);//trim decimals
tip = Math.Round(tip, 2);//trim decimals
totalCost = Math.Round(totalCost, 2);
//Announce results
Console.WriteLine("\nMeal: " + mealCost);
Console.WriteLine(mealGreeting);
Console.WriteLine("Meal: $" + mealCost);
Console.WriteLine("Tax: $" + tax);
Console.WriteLine("Tip: $" + tip);
Console.WriteLine("Total: $" + totalCost);
} while (PlayAgain());
DisplayStr("Enjoy Your Meal!"); //Salutation
}
//MaxBox
public void DisplayChek(String StringNameIs)
{ Console.WriteLine("I am in " + StringNameIs); }//Where are we?
public void DisplayStr(String StrTxt)
{ Console.WriteLine(StrTxt); }
public void DisplayRs()
{ Console.Write("\n\n"); }
public string GetStr(String StrVar)//note - using strings here
{ Console.Write(StrVar);return Console.ReadLine().ToLower().Trim(); }
public double GetDouble(String doubleRequest)// We take in a STRING but we return a DOUBLE
{
Console.WriteLine(doubleRequest + ": "); // HERE we use the STRING to ask for the DOULBE
return double.Parse(Console.ReadLine()); //HERE we RETURN the DOUBLE asked for!
}
public Boolean PlayAgain()
{
Console.Write("\n\nDo you want to play again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
static void Main(string[] args)
{
Program MealCalculator = new Program();
MealCalculator.Play();
//Play keeps file open
//Console.Read();
}
}
}
Console.Read() returns an integer, ReadLine() returns a string.
The ReadLine method, or the KeyAvailable property and ReadKey method are preferable to using the Read method.
If you look at the documentation of both methods: Console.Read() returns the character code of the next character read from the console stream as an integer, whilst Console.ReadLine() returns a line as a string. double.Parse accepts a string parameter, so in the first case there is a type mismatch.
This will not compile as Console.Read() returns an int. You cannot perform .ToLower() on an int.