How do I use Readline input to write a IF/ELSE statement? - c#

I am trying to write a program that accepts users numerical input then output predetermined messages. My question is after I convert the user input from a string to int, how do I use their input in a IF/ELSE statement.
Here's what I have so far:
string UserInput;
Console.Write ("Enter a random number? ");
UserInput =Console.ReadLine();
int x = Convert.ToInt32 (UserInput);
Console.WriteLine (" You entered: " + UserInput);
int x;
if (x < 0)
{
Console.WriteLine (" Error message: Out of range: Enter a number between 0 and 200");
}
{ else if (x >100)
Console.WriteLine (" You are above average");
}
{ else if (x == 100)
Console.WriteLine (" You are average");
}
{
else if (x < 100)
Console.WriteLine (" Sorry but you are below average");
}

The opening parentheses for the else statements should be on the line after the else, not before it. Also your initial if statement needs to check for > 200 too, according to the message printed.
You can also add error checking by using the Int32.TryParse method like this.
string UserInput;
int x;
Console.Write ("Enter a random number? ");
UserInput =Console.ReadLine();
Console.WriteLine (" You entered: " + UserInput);
if (! Int32.TryParse(UserInput, out x))
{
Console.WriteLine ("Invalid data input");
}
else if ((x < 0) || (x>200))
{
Console.WriteLine (" Error message: Out of range: Enter a number between 0 and 200");
}
else if (x >100)
{
Console.WriteLine (" You are above average");
}
else if (x == 100)
{
Console.WriteLine (" You are average");
}
else if (x < 100)
{
Console.WriteLine (" Sorry but you are below average");
}

Let me suggest one way. This way is cleaner and contains error handling. I think you should pass a C# tutorial. Cheers.
public static void Main(string[] args)
{
Console.Write("Enter a random number? ");
string userInput = Console.ReadLine();
Console.WriteLine(" You entered: " + userInput);
try
{
int input = int.Parse(userInput);
PrintMessage(input);
}
catch (Exception)
{
Console.WriteLine(" Error message: Your input is not a number");
}
}
private static void PrintMessage(int input)
{
if (input < 0)
{
Console.WriteLine(" Error message: Out of range: Enter a number between 0 and 200");
}
else if (input > 100)
{
Console.WriteLine(" You are above average");
}
else if (input == 100)
{
Console.WriteLine(" You are average");
}
else
{
Console.WriteLine(" Sorry but you are below average");
}
}

Did you try to input directly in to the function :
if (Convert.ToInt32 (UserInput) < 0)
{
Console.WriteLine (" Error message: Out of range: Enter a number between 0 and 200");
}
else if Convert.ToInt32 (UserInput) >100) {
Console.WriteLine (" You are above average");
}
else if (Convert.ToInt32 (UserInput) == 100) {
Console.WriteLine (" You are average");
}
else if (Convert.ToInt32 (UserInput) < 100) {
Console.WriteLine (" Sorry but you are below average");
}

Related

C# While loop only returns one iteration regardless of input

Trying to write a simple set of code that converts from fahrenheit into celsius, and there are three set conditions that determines what happens. Either it's too cold, just right or too hot. For some reason no matter the input, it will only reply and say it is too cold. I can't really figure out why.
Here's the code so far;
{
class Program
{
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5 / 9);
return celsius;
}
static void Main(string[] args)
{
Console.WriteLine("Please enter the desired temperature: ");
int fahrenheit = Convert.ToInt32(Console.ReadLine());
int celsius = FahrenheitToCelsius(fahrenheit);
while (celsius != 75)
if (celsius < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.");
Console.ReadLine();
}
else if (celsius > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.");
Console.ReadLine();
}
else if (celsius == 75)
{
Console.WriteLine("Optimal input! Begin heating up.");
break;
}
else
{
Console.WriteLine("Invalid input! Please input a temperature.");
}
}
}
}
maybe You only getting same message because you haven't change value of celsius
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5 / 9);
return celsius;
}
static void Main(string[] args)
{
Console.WriteLine("Please enter the desired temperature: ");
int fahrenheit = Convert.ToInt32(Console.ReadLine());
int celsius = FahrenheitToCelsius(fahrenheit);
Console.WriteLine("C = " + celsius);
int i = 0;
while (celsius != 75) {
if (i>0)
{
int x = Convert.ToInt32(Console.ReadLine());
celsius = FahrenheitToCelsius(x);
}
if (celsius < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.");
}
else if (celsius > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.");
}
else if (celsius == 75)
{
Console.WriteLine("Optimal input! Begin heating up.");
break;
}
else
{
Console.WriteLine("Invalid input! Please input a temperature.");
}
i++;
}
}
}
First, Fix your conversion. When converting from one unit to an other one should not remove the decimal value.
static double FahrenheitToCelsius(double f) => (f - 32) * 5.0 / 9.0;
Now lets talk about your if/else. In your code
T <= 163 is too cold;
T = 164,165,166,169,170 are all invalid Temperature;
T >= 171 is too hot;
There is not reason to have those invalid right in the middle of the range.
And there is no explanation on Invalid temp so just drop it.
Is there a number that can satisfy multiple of those condition?
x < 73, x > 77, x ==75...
We can safely drop all the else.
if (tempC < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.\n");
}
if (tempC > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.\n");
}
if (tempC == 75)
{
Console.WriteLine("Optimal input! Begin heating up.\n");
}
Using a Do/While loop we have :
static void Main(string[] args)
{
double tempC , tempF;
do
{
Console.WriteLine("Please enter the desired temperature: ");
tempF = Convert.ToDouble(Console.ReadLine());
tempC = FahrenheitToCelsius(tempF);
Console.WriteLine($"{tempF,4:F}°F, {tempC,4:F}°C");
if (tempC < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.\n");
}
if (tempC > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.\n");
}
if (tempC == 75)
{
Console.WriteLine("Optimal input! Begin heating up.\n");
}
}
while (tempC != 75);
}
Nb renamed the variable from Fahrenheit and Celsius to tempF and tempC.
Temperatur unit find is the while are : C, F, K, R, De, N, Re, Ro.
I'm not sure one can write the name of those without google.

To simplify the code (for a beginner)

I'm on my first week of studying C#.
I guess there should be some way to use 1 "While()" condition instead of 2 in the code below. Is there any way to make my code more simple:
/* ask the user to guess a number.
any number between 10 and 20 is the RIGHT choice,
any other number outside of that scope is WRONG. */
int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();
if (answer == "Q" || answer == "q")
Console.WriteLine();
else
{
num = Convert.ToInt32(answer);
while (num < 10)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
while (num > 20)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Your number is {0} and it's RIGHT", num);
Console.ReadKey();
}
You can use the OR operator to combine both conditions:
/* ask the user to guess a number.
any number between 10 and 20 is the RIGHT choice,
any other number outside of that scope is WRONG. */
int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();
if (answer == "Q" || answer == "q")
Console.WriteLine();
else
{
num = Convert.ToInt32(answer);
while (num < 10 || num > 20)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Your number is {0} and it's RIGHT", num);
Console.ReadKey();
}

Expected class, delegate, enum, interface or struct

Queston is answered thanks for the help :)
I made a code with multiple methods in a class but when I try to run it it says
Expected class, delegate, enum, interface, or struct
on the two methods that are not the main methods. I read around and found that someone had the same problem and the case was that the methods weren’t in the class. But couldn't figure out how to fix that. Any tips?
PS: I’m pretty new to coding ;)
using System;
namespace Testing
{
public class Calculator
{
public static void Main (string[] args )
{
string answer;
Console.WriteLine ("Would you like to divide or multiply? Type your choice.");
Start:
answer = (Console.ReadLine ());
if (answer == "multiply")
{
MultiplyingMethod;
}
{
else if (answer == "divide")
{
DividingMethod;
}
}
else
{
Console.WriteLine ("Please type multiply or divide.");
goto Start;
}
}
}
public static void DividingMethod ()
{
double num01;
double num02;
Console.Write ("Enter a number to be divided");
num01 = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Enter a number to divide by");
num02 = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine (num01 + " divided by " + num02 + " is equal to " + num01 / num02);
Console.WriteLine ("");
Console.ReadKey ();
}
public static void MultiplyingMethod ()
{
double num01;
double num02;
Console.Write ("Enter a number to be multiplied");
num01 = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Enter a numeber to multiply by");
num02 = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine (num01 + " multiplied by " + num02 + " equals " + num01 * num02);
Console.WriteLine ("");
Console.ReadKey ();
}
}
}
Working version:
public static void Main(string[] args)
{
string answer;
Console.WriteLine("Would you like to divide or multiply? Type your choice.");
while (true)
{
answer = (Console.ReadLine());
if (answer == "multiply")
{
MultiplyingMethod();
break;
}
else if (answer == "divide")
{
DividingMethod();
break;
}
else
{
Console.WriteLine("Please type multiply or divide.");
}
}
}
public static void DividingMethod()
{
Console.Write("Enter a number to be divided");
double num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number to divide by");
double num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " divided by " + num02 + " is equal to " + num01/num02);
Console.WriteLine("");
Console.ReadKey();
}
public static void MultiplyingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be multiplied");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a numeber to multiply by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " multiplied by " + num02 + " equals " + num01*num02);
Console.WriteLine("");
Console.ReadKey();
}
Call a method with no parameters like MultiplyingMethod(); instead of MultiplyingMethod;. Thats no valid C#
Please don't use goto. It makes your code messy. Take a look at loops
You should call the methods with ().
Write MultiplyingMethod(); instead of MultiplyingMethod(); and
DividingMethod(); instead of DividingMethod;
public static void Main(string[] args)
{
string answer;
Console.WriteLine("Would you like to divide or multiply? Type your choice.");
Start:
answer = (Console.ReadLine());
if (answer == "multiply")
{
MultiplyingMethod();
}
else if (answer == "divide")
{
DividingMethod();
}
else
{
Console.WriteLine("Please type multiply or divide.");
goto Start;
}
}
public static void DividingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be divided");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a number to divide by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " divided by " + num02 + " is equal to " + num01 / num02);
Console.WriteLine("");
Console.ReadKey();
}
public static void MultiplyingMethod()
{
double num01;
double num02;
Console.Write("Enter a number to be multiplied");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a numeber to multiply by");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num01 + " multiplied by " + num02 + " equals " + num01 * num02);
Console.WriteLine("");
Console.ReadKey();
}
In addition, never use goto, it is not good!
There are several issues with this code:
Calling functions should be done with the syntax: funcname(params). So DividingMethod; becomes DividingMethod();
Try not to use goto (it sounds easy but makes your code really hard to read and debug)
Too many brackets
if (answer == "multiply")
{
MultiplyingMethod;
}
{
else if (answer == "divide")
{
DividingMethod;
}
}
Should be:
if (answer == "multiply")
{
MultiplyingMethod();
}
else if (answer == "divide")
{
DividingMethod();
}

C# Console Output Formatting

I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.

Refactoring to remove try/catch

Any ideas on a good way to refactor this so that my code acts the same, but without the whole throwing and catching my own exception?
public Int32 ChooseNextColor(Int32 numColors)
{
int? nextColor = null;
while (nextColor == null)
{
Console.Write("Please enter your next color selection: ");
string input = Console.ReadLine();
try
{
nextColor = Convert.ToInt32(input);
if (nextColor > numColors || nextColor < 0)
throw new ArgumentOutOfRangeException();
}
catch
{
nextColor = null;
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
}
return (nextColor.Value);
}
EDIT: The try/parse method is exactly what I am looking for.
In response to John's title edit -> I should have posted more information to begin with, and that would have been "getting rid of the try/catch all together is best". So with that in mind, I changed the title.
Try
int nextColor;
input = Console.ReadLine();
while( ! Int32.TryParse( input, out nextColor )
|| nextColor > numColors
|| nextColor < 0 )
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
input = Console.ReadLine();
}
warning, not tested!
public int ChooseNextColor(int numColors)
{
while (true)
{
Console.Write("Please enter your next color selection: ");
string input = Console.ReadLine();
int color;
if (!int.TryParse(input, out color) || color > numColors || color < 0)
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
else
{
return color;
}
}
}
.NET provides TryParse for just this reason.
You can use Int32.TryParse() or
if (nextColor > numColors || nextColor < 0)
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
return null;
}
If you want to avoid exception, you should use int.TryParse method instead of Convert.ToInt32().
public Int32 ChooseNextColor(Int32 numColors)
{
var success = false;
while (!success)
{
Console.Write("Please enter your next color selection: ");
int nextColor;
var input = Console.ReadLine();
success = int.TryParse(input, out nextColor);
if (success && nextColor > 0 && nextColor < numColors) return nextColor;
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
throw new ApplicationException("The thing that should not be.");
}

Categories

Resources