C# switch statement string to char error - c#

using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;
// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");
//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);
// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer
//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();
switch (action) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-":
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*":
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/":
Console.WriteLine("Result is > ", number1 / number1);
break;
default:
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}
I'm trying to get this switch statement to work but it keeps coming up with error, can't change string to char. I don't see where I have tried to change a string to char.

Use
action = Console.ReadKey().KeyChar;
instead of
action = Console.ReadLine();
&
case "+": to case '+':

you declare
char action;
as a char Type but
switch (action)
{
case "+": // here you compare it with a string.
....
case "-": // here you compare it with a string.
....
case "*": // here you compare it with a string.
....
case "/": // here you compare it with a string.
...
action = Console.ReadLine(); //here you try to set a string
replace char action; with string action;

You may find useful to remove swicth at all and implement a dictionary instead:
Dictionary<String, Func<Double, Double, Double>> Actions = new {
{"+", (x, y) => x + y},
{"-", (x, y) => x - y},
{"*", (x, y) => x * y},
{"/", (x, y) => x / y},
};
...
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();
Func<Double, Double, Double> func;
if (Actions.TryGetValue(action, out func))
Console.WriteLine("Result is > ", func(number1, number2));
else
Console.WriteLine("ERROR INVALID INPUT");
if you have a lot of actions (e.g. power **, reminder % etc.) dictionary implemenation is more readable.

using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;
// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");
//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);
// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer
//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
var readaction = Console.ReadLine();
string actionString = readaction.ToString();
switch (actionString) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-" :
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*" :
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/" :
Console.WriteLine("Result is > ", number1 / number1);
break;
default :
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}

Related

How do I get my program to correctly display decimal numbers

using System.Globalization;
namespace MathOperations
{
class Program
{
static void Main(string[] args)
{
bool use_again = true;
Console.WriteLine("Welcome to my own calculator program");
while (use_again == true)
{
Console.WriteLine();
Console.WriteLine("Please input the first number : ");
double number1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please input the second number : ");
double number2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Please input an option");
Console.WriteLine("Add : +");
Console.WriteLine("Substract : -");
Console.WriteLine("Multiply : *");
Console.WriteLine("Devide : /");
char operation_symb = Convert.ToChar(Console.ReadLine());
double result = 0;
switch (operation_symb)
{
case '+':
result = Math.add(number1, number2);
break;
case '-':
result = Math.Substract(number1, number2);
break;
case '*':
result = Math.Multiply(number1, number2);
break;
case '/':
while (number2 == 0)
{
Console.WriteLine("You can't devide by zero idiot");
Console.WriteLine("Please input a valid option");
number2 = Convert.ToDouble(Console.ReadLine());
if (number2 == 0)
{
continue;
}
result = Math.Devide(number1, number2);
}
break;
default:
Console.WriteLine("That's not a valid option");
break;
}
Console.WriteLine($"The result is {number1} {operation_symb} {number2} = {result.ToString("F10", CultureInfo.CurrentCulture)}");
Console.WriteLine("Would you like to use the calculator again?(Y/N)");
string answer;
answer = Console.ReadLine().ToUpper();
answer = "";
switch (answer)
{
case "Y":
use_again = true;
break;
case "N":
use_again = false;
Console.WriteLine("Thanks for using me");
Environment.Exit(0);
break;
default:
Console.WriteLine("That's not a vailid opetion");
answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
use_again = true;
}
else if (answer == "N")
{
use_again = false;
}
break;
}
}
}
}
}
class Math
{
public static double add(double number1, double number2)
{
return number1 + number2;
}
public static double Substract(double number1, double number2)
{
return number1 - number2;
}
public static double Multiply(double number1, double number2)
{
return number1 * number2;
}
public static double Devide(double number1, double number2)
{
return number1 / number2;
}
}
I am a beginner in C# and I have made this calculator program but when I for example devide 1 by 2 the output will be 0.0000000000. What do you think is the problem with the above code. For the other operations the decimal number work properly. Btw can you not use ChatGPT to answer this question please
You get a output value of 0 because the while statement in the switch case return false if number2 is not 0.
Change your divide switch case with that :
case '/':
while(number2 == 0){
Console.WriteLine("You can't devide by zero idiot");
Console.WriteLine("Please input a valid option");
number2 = Convert.ToDouble(Console.ReadLine());
}
result = Math.Devide((double)number1, (double)number2);
break;

How can I use the parameterized method in my code or get the result from the method?

We need to create a simple calculator using parameterized constructor/methods
//I declared some local variables for the parameter
Console.WriteLine("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter second number: ");
double num2= Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter operator: ");
char operation = Convert.ToChar(Console.ReadLine());
double result;
//I used switch-case for the method
static void Calcu(char operation, double num1, double num2, double result)
{
switch (operation)
{
case '+':
result = num1 + num2;
Console.WriteLine("Sum: " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine("Difference: "+ result);
break;
case '*':
result = num1 * num2;
Console.WriteLine("Product: "+ result);
break;
case '/':
result = num1 / num2;
Console.WriteLine("Quotient: "+ result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
}
I am having trouble in getting the result from the method and printing the result outside the method
You need to specify that your method returns something, right now it returns nothing void.
Changing void to double signals that this method will return a double.
You are also passing the result into the Calcu() method which I doubt you want. You should specify the result as a variable within the method then return that variable.
I'm guessing this is what you mean.
static double Calcu(char operation, double num1, double num2)
{
double result;
switch (operation)
{
case '+':
result = num1 + num2;
Console.WriteLine("Sum: " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine("Difference: "+ result);
break;
case '*':
result = num1 * num2;
Console.WriteLine("Product: "+ result);
break;
case '/':
result = num1 / num2;
Console.WriteLine("Quotient: "+ result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
return result
}
Then take in your variables, and then pass them to the method.
//I declared some local variables for the parameter
Console.WriteLine("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter second number: ");
double num2= Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter operator: ");
char operation = Convert.ToChar(Console.ReadLine());
Calcu(operation, num1, num2);
EDIT: sorry terrible formatting

Try-Catch Formatting C#

I'm trying to make a fully functioning calculator application for a school assignment. To do that though I need to use try-catch to handle the DivideByZero error this is my code right now:
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
but it's not working. It seems to make my code at the top invalid. Does anybody know how to format it properly?
P.S. Full code here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator_MK._2
{
class Program
{
static void Main(string[] args)
{
Calculator();
}
private static void Calculator()
{
decimal num1;
decimal num2;
string operation;
decimal result;
decimal num3;
decimal num4;
Console.WriteLine("This is IK's Calculator program that should work if you do everything I say");
Console.ReadLine();
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
if (operation == "x")
{
result = num1 * num2;
Console.WriteLine("{0} * {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "/")
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "+")
{
result = num1 + num2;
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "-")
{
result = num1 - num2;
Console.WriteLine("{0} - {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "Fs")
{
int a = 0;
int b = 1;
int c = 1;
Console.WriteLine(a);
Console.WriteLine(b);
for (; c <= 34; c = a + b)
{
Console.WriteLine(c);
a = b;
b = c;
Console.WriteLine();
}
}
if (num2 == 0)
{
Console.WriteLine("Can't divide by zero fool");
}
}
}
}
The try block has to be around the code that causes the exception, in your case this is
result = num1 / num2;
But it would be better to check there for 0 before you call this line and therefore avoid the exception.
The problem you have is that you have declared the try/catch in the wrong place in the application:
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
All that is going on here are string to number conversions. There are no mathematical operations that could result in DivideByZeroException exceptions.
Instead, you could wrap the divide operation and anything after it you don't want to run if there is an exception:
else if (operation == "/")
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
catch (DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
That said, it is not a good practice to allow exceptions to happen in C# if they can be avoided. In this case, you only need to check the divisor to ensure it is not zero to avoid an exception from occurring.
else if (operation == "/")
{
if (num2 != 0)
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
You have to try the operation itself and not the selection of the operation:
else if (operation == "/")
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
catch(DivideByZeroException ex)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
Right now you try to read inputs from the User. If the user inputs something wrong whichc would throw an exception, your try block would trigger but the catch wont, because you are looking for a DivideByZeroException, which wont occur by input

calculation program and console.read() input stream

is there's something wrong with my code below?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num1 = 0, num2 = 0, rslt = 0;
char oprtr;
Console.Write("Enter calculation: ");
num1 = Convert.ToInt32(Console.Read());
oprtr = Console.ReadKey().KeyChar;
num2 = Convert.ToInt32(Console.Read());
switch (oprtr)
{
case '+':
rslt = num1 + num2;
break;
case '-':
rslt = num1 - num2;
break;
case '*':
rslt = num1 * num2;
break;
case '/':
rslt = num1 / num2;
break;
default:
break;
}
Console.Write("rslt: {0}", rslt);
Console.WriteLine();
Console.ReadKey();
return;
}
}
}
after i compile and run it, the result is 0
it looks like there's nothing wrong with my code.
don't know what's wrong with my code
You need to use Console.ReadLine() instead of Console.Read(). Console.Read() reads the pressed key code not the value.
Replace the following lines
Console.Write("Enter calculation: ");
num1 = Convert.ToInt32(Console.Read());
oprtr = Console.ReadKey().KeyChar;
num2 = Convert.ToInt32(Console.Read());
with
Console.Write("Enter calculation");
Console.Write("\nEnter 1st Operand: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Operator: ");
oprtr = Console.ReadKey().KeyChar;
Console.Write("\nEnter 2nd Operand: ");
num2 = Convert.ToInt32(Console.ReadLine());
EDIT:
Use int.TryParse method to avoid exception because if user press any alphabet or special character then it cannot be store into integer.
Example
int num1;
if (!int.TryParse(Console.ReadLine(), out num1)
{
Console.WriteLine("Invalid Number");
}
else
{
//num1 is ready for calculations
}
Another thing, you should avoid integers because for division, integer/integer = integer, i-e 5/2 = 2 but it should 2.5

simple calculator in C# like this 6+4

these are the variables I used to save data in
int num1 = int.Parse(Console.ReadLine());
string sign = Console.ReadLine();
int num2 = int.Parse(Console.ReadLine());
the if statement that check the input's
how to make it simple
if (sign == "+")
{
Console.WriteLine(num1 + num2);
}
else if (sign == "-")
{
Console.WriteLine(num1 - num2);
}
else if (sign == "*")
{
Console.WriteLine(num1 * num2);
}
else if (sign == "/")
{
Console.WriteLine(num1 / num2);
}
else
{
Console.WriteLine("Wrong operation sign ...");
}
Console.ReadLine();
How to show the output in the form num1 sign num2 = num3 e.g. "6 + 4 = 10" in the console window?
Use string formatting:
Console.WriteLine("{0} {1} {2} = {3}",num1, sign, num2, num1 + num2);
For more information take a look at: Composite Formatting and also Console.WriteLine(String, Object) Method
Save your result to a variable outside of your if/else statement so that you can "dynamically" build your output at the end.
var result = 0;
if (sign == "+")
{
result = num1 + num2;
}
else if (sign == "-")
{
result = num1 - num2;
}
else if (sign == "*")
{
result = num1 * num2;
}
else if (sign == "/")
{
result = num1 / num2;
}
else
{
Console.WriteLine("Wrong operation sign ...");
}
Console.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result);
Console.ReadLine();
To print out the result u can do
Console.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result)
where result is the result of the operation. (e.g. 6 in your example)
"how to make it simple?"
You can abuse the DataTable.Compute method:
var answer = new DataTable().Compute(num1.ToString() + sign + num2.ToString(), null);
"How to show the output..."
See String.Format / console.WriteLine overload as mentioned by Selman22, eg:
Console.WriteLine("{0} {1} {2} = {3}",num1, sign, num2, answer);
How your program could be written:
Console.WriteLine("Please type a simple sum:");
string sum = Console.Readline();
var answer = new DataTable().Compute(sum, null);
Console.WriteLine("{0} = {1}",sum, answer);
Console.Readline();

Categories

Resources