Entered wrong value. goto Start; - c#

Edit.
Based on the answers received I realized that I am asking more than I know about at this early stage in my learning and as such, I have decided to forget this question until I have learnt and understand more. I do not want to overstep and confuse myself.
Just a newbie looking for some guidance.
From a previous question I asked here, I was introduced to the goto Start; in the switch statement.
I started using it and it had me thinking that I wanted the program to go to the start in the event the user entered an invalid input. Example, in my calculator below, if the user enters something other than a number, how do I get the program to disregard the input and prompt the user again to enter a number? Maybe even display an "invalid input. please try again" to the user.
Right now, if anything but a number is entered, the console crashes and throws me an error.
Thanks in advance for the assistance
int num1, num2, output;
string op;
Console.Write("\n\n");
Console.WriteLine("Calculator\n");
Console.WriteLine("=============");
Console.Write("\n\n");
Start:
Console.Write("Please enter first number:");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Operator:
Console.WriteLine("Please select operator: ");
Console.WriteLine("\nAddition : +");
Console.WriteLine("Multiplication: *");
Console.WriteLine("Division: /");
Console.WriteLine("Subtraction: -");
Console.Write("Enter Operator: ");
op = Console.ReadLine();
switch (op)
{
case "+":
output = num1 + num2;
Console.WriteLine("{0} added to {1} = {2}", num1, num2, output);
break;
case "*":
output = num1 * num2;
Console.WriteLine("{0} multiplied by {1} = {2}", num1, num2, output);
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero. Please try again");
goto Start;
}
else
{
output = num1 / num2;
Console.WriteLine("{0} divided by {1} = {2}", num1, num2, output);
break;
}
case "-":
output = num1 - num2;
Console.WriteLine("{0} minus{1} = {2}", num1, num2, output);
break;
default:
Console.WriteLine("You entered an invalid operator. Please try again\n");
goto Operator;
}
Console.WriteLine("\nPress enter to continue....");
Console.ReadLine();

Please, whatever you do, do NOT use goto. Ever. Maybe except in switch to fall down to other case, but even that should be very rare. It makes your code unreadable, confusing and hard to maintain. Please see spaghetti code.
That said, you should do Int32.TryParse instead of Convert if you are not sure if the input is valid:
int num1;
do
{
Console.Write("Please enter first number:");
} while (!Int32.TryParse(Console.ReadLine(), out num1));
And change your switch to something like this (to avoid goto):
bool inputOk = false;
while (!inputOk)
{
Console.WriteLine("Please select operator: ");
//...
op = Console.ReadLine();
inputOk = true;
switch (op)
{
//...
default:
Console.WriteLine("You entered an invalid operator. Please try again\n");
inputOk = false;
break;
}
}

Untested, but this may be what you want:
Start:
Console.Write("Please enter first number:");
if (!int.TryParse(Console.ReadLine(), out num1))
goto Start;
//num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Operator:
...
And perhaps the same for num2, if you need.

The best way to achieve this is through the use of EXCEPTION. Since you are learning, I would not provide a sample code on how to do it but would want you to read about it here and here

goto inside a switch tries to go to the defined case. In your example there is no start case so it doesn't know where to go.
more info here.
I would suggest using methods though.

I don't think goto statements are suitable in this situation. Your code can get really messy if you have a lot of them. Using FormatException isn't recommended either, since throwing an exception takes a long time.
I think you should use Int32.TryParse instead.
Here's a piece of sample code. See if you can apply this to your program.
int input;
while(true) {
Console.WriteLine("Please enter a number");
bool succeeds = Int32.TryParse(Console.ReadLine(), out input);
if (!succeeds) {
Console.WriteLine("Input Invalid! Try again!");
} else {
break;
}
}
// make use of input here

int num1, num2, output;
string op;
Console.Write("\n\n");
Console.WriteLine("Calculator\n");
Console.WriteLine("=============");
Console.Write("\n\n");
Start:
do
{
Console.Write("Please enter valid first number:");
} while (!int.TryParse(Console.ReadLine(), out num1));
do
{
Console.Write("Please enter valid second number:");
} while (!int.TryParse(Console.ReadLine(), out num2));
Operator:
Console.WriteLine("Please select operator: ");
Console.WriteLine("\nAddition : +");
Console.WriteLine("Multiplication: *");
Console.WriteLine("Division: /");
Console.WriteLine("Subtraction: -");
Console.Write("Enter Operator: ");
op = Console.ReadLine();
switch (op)
{
case "+":
output = num1 + num2;
Console.WriteLine("{0} added to {1} = {2}", num1, num2, output);
break;
case "*":
output = num1 * num2;
Console.WriteLine("{0} multiplied by {1} = {2}", num1, num2, output);
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero. Please try again");
goto Start;
}
else
{
output = num1 / num2;
Console.WriteLine("{0} divided by {1} = {2}", num1, num2, output);
break;
}
case "-":
output = num1 - num2;
Console.WriteLine("{0} minus{1} = {2}", num1, num2, output);
break;
default:
Console.WriteLine("You entered an invalid operator. Please try again\n");
goto Operator;
}
Console.WriteLine("\nPress enter to continue....");
Console.ReadLine();

Related

A problem with getting/printing answers in a C# calculator

I'm trying to make simple projects for learning C# and have tried to make a simple console calculator. I have only found this current error when getting to the getting/printing the answer bit when test-running my program, so I have no idea if there are any other errors/things that will or may not work or run properly/as intended. So if there are any of those, please let me know and if you want to you can fix them yourself. It only recognized the error when it reached that specific line of code, and otherwise will run the program until it reaches the error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
string num1;
string num2;
string condition;
string answer;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = Console.ReadLine();
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = Console.ReadLine();
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
answer = num1 + condition + num2;
Convert.ToInt32(answer);
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
answer = null;
num1 = null;
num2 = null;
condition = null;
}
}
}
}
When facing problems like this one - the routine is too complex to be tested:
if there are any other errors/things that will or may not work"
split routine into smaller ones: start extracting methods.
// Get integer value from user
public static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value, please, try again.");
}
}
// Get character operator ('+', '-' etc.) from user
public static char ReadOperator(string title, string operators) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string input = Console.ReadLine().Trim();
if (input.Length == 1 && operators.Contains(input[0]))
return input[0];
Console.WriteLine("Sorry, not a valid operator, please, try again.");
}
}
Now we are ready to implement Main method:
static void Main(string[] args) {
while (true) {
int num1 = ReadInteger("Enter a number: ");
char op = ReadOperator("Enter a condition: ", "+-*/");
int num2 = ReadInteger("Enter your second number: ");
//TODO: I've skipped error handling (zero division, overflow)
int answer =
op == '+' ? num1 + num2 :
op == '-' ? num1 - num2 :
op == '*' ? num1 * num2 :
op == '/' ? num1 / num2 : 0;
Console.WriteLine($"{num1} {op} {num2} = {answer}");
//TODO: it's a right place here to ask user if (s)he wants to continue
Console.WriteLine();
}
}
You receive input (condition) as a string
cant do this : answer = num1 + condition + num2 because those variables are
string
you have to check that with switch , for example :
int num1 = 0, num2 = 0, answer = 0;
string condition;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = int.Parse(Console.ReadLine());
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
switch (condition)
{
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
default:
Console.WriteLine("error : unknown operator");
break;
}
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
}
You can't do this line because all the variables are strings and not the real values (e.g: num1 & num2 should ints/doubles... and condition should be a real operator).
answer = num1 + condition + num2;
Also, you can't do it because let's assume the user inputs the multiplication sign, and then the string of "*" is not equal to the sign of *.
Instead, you can do some switch-case statements to check the value of the condition variable. Also, you need to make sure num1 & num2 are numbers (you can parse/try-parse them to a number (int/double...)). You will also have to parse them to another variables as they are strings.
switch (condition)
{
case '*':
answer = numX * numY;
break;
case "/":
// Validate that numY is not 0 to avoid [DivideByZeroException][1]
answer = numX / numY;
break;
...
}
Note, it is just one way to do it and I just gave you a small example that might help you to continue.
I would also offer you to make a default case (in case that the input of the user is not something you expect, in this case, you may ask him again to write an input because the current input is invalid).

Pseudocode for switch statement in c#

How do I write the pseudocode for a switch (case) statement in C#?
switch (option)
{
case 1:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 + num2;
Console.WriteLine(result);
break;
case 2:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 - num2;
Console.WriteLine(result);
break;
case 3:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 * num2;
Console.WriteLine(result);
break;
default:
Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
break;
}
So, if I was going to write this, I'd start with an enumerated type for the operations:
public enum ArithmeticOperation
{
Add,
Subtract,
Multiply,
Divide,
}
I'd write a little helper function:
private static string ShowEnumOptions<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException($"Type: {typeof(T).ToString()} must be an enumerated type");
}
var options = Enum.GetNames(typeof(T));
return string.Join("/", options);
}
(the newest version of C# (which I don't use yet) allows a System.Enum constraint on a generic type parameter which would simplify this)
Then I'd write my main program to look like this:
static void Main(string[] args)
{
while (true)
{
ArithmeticOperation operation = default(ArithmeticOperation);
var goodOperation = false;
while (!goodOperation)
{
Console.Write(
$"Enter operation (one of [{ShowEnumOptions<ArithmeticOperation>()}] or \"Quit\"): ");
var response = Console.ReadLine();
if (string.Equals(response, "Quit", StringComparison.InvariantCultureIgnoreCase))
{
return; //quit the app
}
if (Enum.TryParse<ArithmeticOperation>(response, true, out operation))
{
goodOperation = true;
}
}
double value1 = 0.0;
double value2 = 0.0; //initialize them to keep the compiler happy
var goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the first number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value1))
{
goodDouble = true;
}
}
goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the second number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value2))
{
goodDouble = true;
}
}
//ok, got an operation and two numbers
double result = 0.0;
switch (operation)
{
case ArithmeticOperation.Add:
result = value1 + value2;
break;
case ArithmeticOperation.Subtract:
result = value1 - value2;
break;
case ArithmeticOperation.Multiply:
result = value1 * value2;
break;
case ArithmeticOperation.Divide:
if (value2 == 0.0)
{
Console.WriteLine("Division by zero is invalid");
result = double.NaN; //NaN means "not a number"
break;
}
result = value1 / value2;
break;
}
Console.WriteLine($"Result is {result}");
}
}
Note that I check all input for validity. Always assume your users will enter bad data. Also note that I check my double for equality with zero. Checking for floating point equality is usually a bad idea, but it's the right thing to do here.
Then, as pseudo code, all I'd write would be:
// Get the operation (one of add/subtract/multiply or divide) - or allow the user to quit
// Get each of value1 and value2 as doubles
// Based on the operation, calculate the result (pay attention to division by zero)
// Show the result
// Loop back and let the user try again (or quit)
Pseudocode is basically writing what you're trying to do in comments. What your professor was probably trying to teach you is to make a bunch of comments to plan out the structure of your code, and then write your code. What you have above is already functional code. At the risk of answering your homework question, I'd say it goes something like this:
switch(option)
{
case 1:
//do something
break;
case 2:
//do something else
break;
default:
//what to do if none of the cases are met
break;
}
I don't know what you mean with pseudocode but this code is less repetitive:
double result = 0;
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter a number from 1 to 3");
string input = Console.ReadLine();
switch (input) {
case "1" :
result = num1 + num2;
break;
case "2":
result = num1 - num2;
break;
case "3":
result = num1 * num2;
break;
default:
Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
break;
}
Console.WriteLine("Result = " + result);

How do I check if a variable is equal to a string or an int?

For example, lets say I have and int called input. And then I get input for it. Like this:
input = Console.ReadLine();
But when the user gets prompted, input is a string, and then it gets an error and crashes the program. How do I check if a string was entered for input?
Is there an option for it like if (input.equals(string)) or something like that?
EDIT: I tried doing the TryParse but I think I'm doing it wrong. I posted the code below
string numberOne;
string numberTwo;
double answer;
string operand;
Console.WriteLine("Enter the first number");
numberOne = Console.ReadLine();
if (double.TryParse(numberOne, out double value))
{
Convert.ToInt32(numberOne);
}
else
{
Console.WriteLine("Non integer entered. Please enter a valid number.");
}
Console.WriteLine("Enter the operator");
operand = Console.ReadLine();
Console.WriteLine("Enter the second number");
numberTwo = Console.ReadLine();
if (double.TryParse(numberTwo, out double value2))
{
Convert.ToInt32(numberTwo);
}
else
{
Console.WriteLine("Non integer entered. Please enter a valid number.");
}
switch(operand)
{
case "+":
answer = numberOne + numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "-":
answer = numberOne - numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "*":
answer = numberOne * numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "/":
answer = numberOne / numberTwo;
Console.WriteLine("The answer is " + answer);
break;
default:
Console.WriteLine("Please enter a valid operator such as +, -, *, or /");
break;
}
Console.Readline() always returns a string, however you can do this to check if an integer is inputed and continue asking for correct type of input until user delivers it.
string input = Console.ReadLine();
int parsed;
while (!int.TryParse(input, out parsed))
{
Console.WriteLine("Please enter a number!");
input = Console.ReadLine();
}
//do something with parsed
Console.ReadLine always returns a string. It's doesn't return differently typed things based the content read from console. It's your job to decide if the value entered matches your requirements (in this case it should be something that can be parsed to an int).
You can use int.TryParse to try parsing a string as int without it throwing an exception when parsing fails.
string input = Console.ReadLine();
if(int.TryParse(input, out int value))
{
// value contains an int parsed out of input
}
else
{
// parsing fails, you can do something about that, e.g. ask user for different input
}

Print message when invalid data entered in console application using switch C#

Im trying to write a basic calculator with a main menu and sub menu.
The code is working fine when a valid entry is inputted, but I want an error message to be displayed and then return the user to the main menu when invalid data is entered.
This is what I have done so far. Can someone tell me what am I doing wrong?
static void Main(string[] args)
{
// Main method (only to be used for mainmenu() execution)
MainMenu();
}
// Main Menu method
static void MainMenu()
{
// Declaring variables
// Selection variable, used in user's input to get to the desired operation
int sel;
char letter;
// Main menu styling
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
// Converting user's input to sel's type (byte)
sel = int.Parse(Console.ReadLine());
// Processing sel
switch (sel)
{
case 1:
// Execute Addition()
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!"); //Catch
break;
}
}
static void SecondMenu()
{
char sel2; // Selection variable, used in user's input to get to the desired operation
// Display Menu Options
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
// Converting user's input to sel's type (byte)
sel2 = Convert.ToChar(Console.ReadLine());
// Processing sel
switch (sel2)
{
case 'a':
// Execute Addition()
Addition();
break;
case 's':
// Execute Substraction()
Substraction();
break;
case 'd':
// Execute Division()
Division();
break;
}
}
// Addition Method
static void Addition()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 + num2;
// Printing out the result
Console.WriteLine("RESULT: " +res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
// Substraction Method
static void Substraction()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 - num2;
// Printing out the result
Console.WriteLine("RESULT: " + res);
Console.ReadKey(true);
MainMenu();
}
// Division
static void Division()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 / num2;
// Printing out the result
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
You can call the MainMenu() method in the default part of the switch in it.
switch (sel)
{
case 1:
// Execute Addition()
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format!");
MainMenu();
//Catch
break;
}
It is also recommended to have a condition to exit the program (like a maximum number of invalid inputs).
Something like this works, but you'll have to adjust accordingly to fit your requirements:
int sel;
char letter;
bool valid = false;
do
{
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
sel = int.Parse(Console.ReadLine());
switch (sel)
{
case 1:
SecondMenu();
break;
case 2:
Environment.Exit(0);
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
}
while (valid != true);
You could just do it like this
static void SecondMenu()
{
char sel2; // Selection variable, used in user's input to get to the desired operation
// Display Menu Options
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
sel2 = Convert.ToChar(Console.ReadLine());
switch (sel2)
{
case 'a':
Calc(1);
break;
case 's':
Calc(2);
break;
case 'd':
Calc(3);
break;
default:
Console.WriteLine("Wrong entry! Try again");
MainMenu();
return;
}
}
static void Calc(int f)
{
double num1, num2, res;
try
{
Console.Write("Please enter the first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
num2 = Convert.ToDouble(Console.ReadLine());
switch (f)
{
case 1:
res = num1 + num2;
break;
case 2:
res = num1 - num2;
break;
case 3:
res = num1 / num2;
break;
default:
Console.WriteLine("Wrong entry! Try again");
MainMenu();
return;
}
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
catch
{
Console.WriteLine("Wrong entry! Try again");
MainMenu();
}
}
EDIT: To make sure the first menu wont crash, sorround it with a try catch block
try
{
sel = int.Parse(Console.ReadLine());
switch (sel)
{
case 1:
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
MainMenu();
break;
}
}
catch
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
MainMenu();
}
Your problem was, that it tried to parse a char into an int, what is not possible.
You can either write the switch case in another method and call the main method at the default case after printing the error message,
OR
Use a do-while loop,
Inside do, write the switch cases and put a condition at while to exit the calculator.
For example: 'Enter -1 to exit the calculator' and condition in while x!=-1
Try having a play with this:
static void Main(string[] args)
{
MainMenu();
}
static void MainMenu()
{
int sel = -1;
while (sel != 2)
{
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
sel = int.Parse(Console.ReadLine());
if (sel == 1)
{
SecondMenu();
}
else if (sel != 2)
{
Console.WriteLine("Sorry that is not correct format! Please restart!"); //Catch
}
}
}
static void SecondMenu()
{
var options = new Dictionary<char, Func<double, double, double>>()
{
{ 'a', (x, y) => x + y },
{ 's', (x, y) => x - y },
{ 'd', (x, y) => x / y },
};
while (true)
{
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
char sel = Convert.ToChar(Console.ReadLine());
if (options.ContainsKey(sel))
{
Calculate(options[sel]);
break;
}
}
}
static void Calculate(Func<double, double, double> operation)
{
Console.WriteLine("Please enter the first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
double res = operation(num1, num2);
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadLine();
}

C# program does not evaluate operations and return wrong answers

Community.
I am learning how to program in C#. I wrote this small program that gets the name, age, favorite color, and two numbers from the user. I use Notepad ++ to write the code and run the C# compiler from the windows command prompt. Here is the source code of the program
using System;
class ShowSomething
{
static void Main(string[] args)
{
string name, age, favColor;
int num1,num2, sum, mult, subs;
float div;
Console.Write("What is your name? ");
name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine();
Console.Write("How old are you? ");
age = Console.ReadLine();
Console.WriteLine("So you are " + age, "I thought that you were older!");
Console.WriteLine();
Console.Write("What is your favorite Color? ");
favColor = Console.ReadLine();
Console.WriteLine(favColor + " is a cool color!");
Console.WriteLine();
Console.WriteLine("Nice meeting you, " + name, "Have a good day!");
Console.WriteLine();
Console.WriteLine("Let us do some operations, " + name);
Console.WriteLine();
Console.Write("Please enter a number: ");
num1 = Console.Read();
Console.Write("Please enter another number: ");
num2 = Console.Read();
sum = num1 + num2;
mult = num1 * num2;
subs = num1 - num2;
div = num1 / num2;
Console.WriteLine();
Console.WriteLine("Alright, " + name, "Let us blow up your mind!");
Console.WriteLine();
Console.WriteLine(num1 + "+" + num2, "=" + sum);
Console.WriteLine(num1 + "*" + num2, "=" + mult);
Console.WriteLine(num1 + "-" + num2, "=" + subs);
Console.WriteLine(num1 + "/" + num2, "=" + div);
Console.WriteLine();
Console.WriteLine("Mindblown, Right?");
}
}
When I execute the program almost everything goes alright. However, when the user inputs the first number of the operations, the program skips the second prompt and print a completely different result from the one expected. For example, if I put 0 as the first number the program will jump to the operations and print the following:
//
48+13
48*13
48-13
48/13
Mindblown, right?
//
Do not use Console.Read as it does not do what is expected:
Reads the next character from the standard input stream (and returns the integer value1 that represents it).
Here a good explanation from devshort on why the second call to Console.Read "skips":
If you enter in the value "1" for the first thing, it'll convert that to the ascii representation. Then the carriage return is STILL in the screen [input] buffer, so when you hit the next read (Console.Read) it reads the newline and converts it to a number.
Instead, one approach is to use Console.ReadLine instead (which returns a string) in conjunction with int.Parse or similar ..
1 Hint: the carriage return character has a value of 13.
The ascii that is visually 0 has a byte value of 48. or 0x30. Which explains the 48.
Basically, you're using the wrong function.
Ok, I edited your code a little and added some explanation wy I changed somethings..
string name, age, favColor;
int num1, num2, sum, mult, subs;
float div;
Console.WriteLine("What is your name? ");
//Start a new line and write ..
name = Console.ReadLine();
//Read the whole line
Console.WriteLine("\nHello, {0}", name);
//{0} stands for the first variable you refer to after the, etc
Console.WriteLine("How old are you? ");
age = Console.ReadLine();
Console.WriteLine("\nSo you are {0}, I thought that you were older!", age);
// something new.. \n refers to a "new line", so instead of writing Console.Writeline(); you can use this
Console.WriteLine("What is your favorite Color? ");
favColor = Console.ReadLine();
Console.WriteLine("{0} is a cool color!\n", favColor);
Console.WriteLine("Nice meeting you, {0}", name);
Console.WriteLine("Have a good day!\n");
Console.WriteLine("Let us do some operations, {0}", name);
Console.WriteLine("Please enter a number: ");
num1 = Convert.ToInt16(Console.ReadLine());
//int.TryParse(Console.ReadLine(), out num1);
//Another way is to "try parse", try converting a string to an integer
Console.WriteLine("\nPlease enter another number: ");
num2 = Convert.ToInt16(Console.ReadLine());
//int.TryParse(Console.ReadLine(), out num2);
//Another way is to "try parse", try converting a string to an integer where out is the returning variable
sum = num1 + num2;
mult = num1 * num2;
subs = num1 - num2;
div = num1 / num2;
Console.WriteLine("\nAlright, {0}", name);
Console.WriteLine("Let us blow up your mind!\n");
//Again use {0} ... which writes easier than having to use + every time,
//its not wrong but its easier this way
Console.WriteLine("{0} + {1} = {2}", num1, num2, sum);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mult);
Console.WriteLine("{0} - {1} = {2}", num1, num2, subs);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.WriteLine("\nMindblown, Right?");
Console.ReadLine();
//Console.ReadLine(); at the end to prevent the program from closing

Categories

Resources