Why isn't the char changing the way I Intend it too? - c#

I am new here so please excuse me for the poor formatting,
I wrote a simple calculator in c# but it seems my multiplication and division are not working correctly.
when running the code it works fine until I try to output the answer and then it outputs "Error, Unknown operator" which is what I told it to output when it doesn't identify the operator stored in the operation variable.
here is the code (sorry for dumping so much code, I am not sure what is relevant and what is not):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class MainClass
{
public static void Main(string[] args) // method called "main", when the program starts, this runs
{
start:
// variable declarations
double Num1;
double Num2;
int operationId;
string operationName = "1";
string operationName2 = "1";
Char operation;
double answer;
// choosing an operator
Console.WriteLine("select an operation from the list and type it's associated number:");
Console.WriteLine("1 - sum \n" + "2 - subtraction \n" + "3 - division\n" + "4 - multipication \n");
operationId = Convert.ToInt32(Console.ReadLine());
// checking which operation has been chosen
if (operationId == 1)
{
operationName = "added to";
operationName2 = "added";
operation = '+';
} else if (operationId == 2)
{
operationName = "subtracted from";
operationName2 = "subtracted";
operation = '-';
} else if (operationId == 3)
{
operationName = "divided";
operationName2 = "divided by";
operation = '/';
} else if (operationId == 4)
{
operationName = "multiplied";
operationName2 = "multiplied by";
operation = '*';
} else
{
Console.WriteLine("Invalid option");
goto start;
}
// receving user input
Console.WriteLine("Insert a number to be " + operationName + ":");
Num1 = Convert.ToDouble (Console.ReadLine());
Console.WriteLine("Insert a number to be " + operationName2);
Num2 = Convert.ToDouble(Console.ReadLine());
//calculating answer
if (operation == '+')
{
answer = Num1 + Num2;
}
else if (operation == '-')
{
answer = Num1 - Num2;
}
else if (operationId == '/')
{
answer = Num1 / Num2;
}
else if (operationId == '*')
{
answer = Num1 + Num2;
} else
{
answer = 0000;
Console.WriteLine("Error, Unknown operator \n");
goto start;
}
Console.WriteLine();
Console.WriteLine("The result is:");
Console.WriteLine(answer);
Console.ReadKey();
Console.WriteLine();
goto start;
}
}
}

Your first 2 ifs check operation, the second 2 check operationId. Change the multiply and divide ones to also check operation.
//...
else if (operation == '/')
{
answer = Num1 / Num2;
}
else if (operation == '*')
{
answer = Num1 * Num2; //<-- Change to this from Num1 + Num2
}
//...
And by the way, your multiply block is adding the numbers, not multiplying. I've fixed that in my block above.

I guess the problem is with - 2 conditions are checking operation and 2 conditions are checking operationId. Perhaps you may want to change all the checks to be either with operation or with operationId.
if (operation == '+')
{
answer = Num1 + Num2;
}
else if (operation == '-')
{
answer = Num1 - Num2;
}
else if (operationId == '/')
{
answer = Num1 / Num2;
}
else if (operationId == '*')
{
answer = Num1 + Num2;
} else
{
answer = 0000;
Console.WriteLine("Error, Unknown operator \n");
goto start;
}

Related

How do I make my C# program start again from the top after every time it finishes

guys, I'm a beginner at this, after trying to build this calculator I just wanted to learn how to make it start again I tried using a while loop but unfortunately, I wasn't able to figure it out please help thanks.
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Add an operator");
string op = Console.ReadLine();
Console.Write("Enter another number");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Console.WriteLine(num1 + num2);
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine("Invalid operator");
}
}
}
}
To keep it running, you can add a while(true) to wrap your logic code. this will repeatedly execute the block of code. In case there is a condition where you want to exit the loop, you can achieve this via break
static void Main(string[] args)
{
while (true){
Console.Write("Enter a number");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Add an operator");
string op = Console.ReadLine();
Console.Write("Enter another number");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Console.WriteLine(num1 + num2);
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine("Invalid operator");
}
if (//condition is ok and you want to break out of the loop){
break;
}
}
}
If it is console application,
you could do something like this at the end of your app -
System.Diagnostics.Process.Start("your_prog_name.exe"); Environment.Exit(0);
It should terminate previous process and start it again.
Console window won't disappear.

I Can't call the methods in C# am using [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code
Basic Calculator Using 2 methods
1 is the main method
2 is the operator
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int num1;
int num2; //Variables for equation
string op;
//int Answer;
Console.Write("Enter the first number : ");
num1 = Convert.ToInt32(Console.ReadLine());
//User input for equation
Console.Write("Now enter your second number : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Ok now enter your operation ( x , / , +, -) ");
op = Console.ReadLine();
Methods1(); // This is the error, The error says
// There's no argumen given that corresponds
}
static int Methods1(int num1, int num2, string op)
{
if (op == "+")
{
return num1 + num2;
}
else if (op == "-")
{
return num1 - num2;
}
else if (op == "/")
{
return num1 / num2;
}
else if (op == "*")
{
return num1 * num2;
}
else
{
Console.WriteLine("Invalid Operator");
return 0;
}
}
}
}
You have called the Methods1() method without arguments. Change the code to the following:
using System;
namespace Test_app_1
{
class Program
{
static void Main(string[] args)
{
int num1;
int num2; //Variables for equation
string op;
int Answer;
Console.Write("Enter the first number : ");
num1 = Convert.ToInt32(Console.ReadLine());
//User input for equation
Console.Write("Now enter your second number : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Ok now enter your operation ( * , / , +, -) ");
op = Console.ReadLine();
Answer = Methods1(num1, num2, op); // Now no error...
Console.WriteLine(Answer + "\nPress any key to exit..."); //You forgot to add Console.Writeline
Console.Read(); //Also forgot Console.Read
}
static int Methods1(int num1, int num2, string op)
{
if (op == "+")
{
return num1 + num2;
}
else if (op == "-")
{
return num1 - num2;
}
else if (op == "/")
{
return num1 / num2;
}
else if (op == "*")
{
return num1 * num2;
}
else
{
Console.WriteLine("Invalid Operator");
return 0;
}
}
}
}

How to convert Console.ReadLine() to double in simple calculator ? C# Problem with exception

I used double.Parse and Convert.ToDouble and got the same error
System.FormatException: Input string was not in a correct format.
When I write in console 10.2 or any other double number.
I learnt from a tutorial and I followed it step by step but I have no idea how to solve this.
Also I am using Visual Studio.
Console.WriteLine("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());
Console.Write("Enter operator: ");
string op = Console.ReadLine();
Console.WriteLine("Enter a number: ");
double num2 = double.Parse(Console.ReadLine());
if (op == "+")
{
Console.Write(num1 + num2);
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine("Invalid Operator");
}
The problem might be your culutral setting.
Some countries uses a . others uses a ,
try:
double num2 = double.Parse(Console.ReadLine(), NumberStyles.Any, CultureInfo.InvariantCulture);
or set the separator like:
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
double num2 = DateTime.Parse(Console.ReadLine(), culture);
missing Line in WriteLine in lines 4 and 11
Console.WriteLine("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter operator: ");
string op = Console.ReadLine();
Console.WriteLine("Enter a number: ");
double num2 = double.Parse(Console.ReadLine());
if (op == "+")
{
Console.WriteLine(num1 + num2);
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine("Invalid Operator");
}
this is fixed version as op has the broken version posted

1. How can I get my random number to be different each time it is printed out? 2. Are there any basic things that I can improve upon? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
I am very new to programming as a whole and C# is my first language. I have been working on this project for the past few weeks or so that gives the user 3 options of whether they want to use a random number generator, calculator or roll a dice.
So far everything is going okay. I have been focusing quite a lot on exception handling and commenting to make sure that everything is as clear as possible. One problem that I have come across and am not surer how to fix is that in my dice rolling procedure it prints out the same random dice number x times rather than printing out different random numbers each time. So if you could help me fix that that would be awesome. Here is just the code for that;
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
Also, as I'm a newbie in general, I think some feedback from more experienced users will benefit me as a whole. Is there any mistakes I've made> Any informal rules I have broken? Please let me know I will be very thankful. Here is all of the code;
static void Main(string[] args)
{
Boolean chooseRun = false;
while (chooseRun == false)
{
Console.WriteLine("To use the calculator enter C\nTo use the random number generator enter R\nTo roll a dice enter D");
string chooseProc = Console.ReadLine();
if (chooseProc == "C" || chooseProc == "c")
{
calculator();
chooseRun = true;
}
else if (chooseProc == "R" || chooseProc == "r")
{
numGenerator();
chooseRun = true;
}
else if (chooseProc == "D" || chooseProc == "d")
{
rollDice();
chooseRun = true;
}
else
{
Console.WriteLine("Sorry that was an invalid input. Please try again");
chooseRun = false;
}
}
Console.Write("Goodbye");
Console.ReadKey();
}
/// <summary>
/// Here I have a simple calculator that can do basic functions such as subtraction and then I give them the option to use it again
/// </summary>
static void calculator()
{
int loop = 1;
while (loop == 1)
{
Console.WriteLine("You chose to use the calculator!\nPress the enter key to start"); //Greet the user and give them the option of when they want to start the calculator based upon when they choose to click the enter key
Console.ReadKey(true);
int num1 = 0; //Declaring variables
int num2 = 0;
string operation = "";
int answer;
Boolean gotnum1 = false;
while (gotnum1 == false)
{
Console.Write("Enter the first number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num1 = int.Parse(Console.ReadLine());
gotnum1 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotnum2 = false;
while (gotnum2 == false)
{
Console.Write("Enter the second number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num2 = int.Parse(Console.ReadLine());
gotnum2 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotOpr = false;
while (gotOpr == false)
{
Console.Write("Ok now enter your operation ( x , / , +, -) ");
operation = Console.ReadLine();
switch (operation)
{
case "x":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "X":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "/":
try
{
answer = num1 / num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
}
catch (DivideByZeroException e)
{
Console.WriteLine("You cannot divide by zero");
}
break;
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
default:
Console.WriteLine("Sorry that is an invalid input");
gotOpr = false;
break;
}
}
Console.WriteLine("Do you want to use the calculator again? Select;\nIf you would please enter /Y/\nIf not please enter /N/");
string rerun = Console.ReadLine();
if (rerun.ToUpper() == "N")
{
loop = 0;
}
}
}
/// <summary>
/// This procedure generates a random number and gives the user the option as to whether they would like to generate another
/// </summary>
static void numGenerator()
{
Console.WriteLine("You chose to use the random number generator");
Boolean moreNum = false;
while (moreNum == false)
{
Random r = new Random();
int n = r.Next();
Console.WriteLine(n);
Console.WriteLine("If you would like another number enter Y, otherwise please enter N");
string rerun = Console.ReadLine();
if (rerun == "Y" || rerun == "y")
{
moreNum = false;
}
else if (rerun == "N" || rerun =="n")
{
moreNum = true;
}
}
}
/// <summary>
/// In this procedure a virtual dice is rolled of a user inputted number of times, this too gives the user the option to roll the dice again after rolling it x times
/// </summary>
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
You should create the Random object only once, typically create is in a static field (if you create it many times, it would generate the same values every time)
static Random rnd = new Random();

why 2 is automatically converted to 299?

I'm new:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private static void Main()
{
Console.WriteLine("Welcome to my calculator");
Console.WriteLine("Calculator only supports -,+,/,*");
Console.WriteLine("Calculator V1.20 alpha");
Console.WriteLine("Enter your first number");
int num1 = Console.ReadKey().KeyChar;
Console.WriteLine("Enter your operator");
Console.WriteLine();
char operation = Console.ReadKey().KeyChar;
Console.WriteLine("Enter your second number");
Console.WriteLine();
int num2 = Console.ReadKey().KeyChar;
//the answer variables
int answersubtract = num1 - num2;
int answeradd = num1 + num2;
int answermulti = num1 * num2;
int answerdiv = num1 / num2;
if (operation == '-')
{
Console.WriteLine(answersubtract);
}
else if (operation == '+')
{
Console.WriteLine(answeradd);
}
else
{
if (operation == '*')
{
Console.WriteLine(answermulti);
}
else
{
if (operation == '/')
{
Console.WriteLine(answerdiv);
}
}
}
Console.ReadKey();
}
}
}
Edit:
The input I am sending to the program is:
1+2
int num1 = Console.ReadKey().KeyChar;
You are reading a character, not a number. Review the docs for ConsoleKeyInfo.KeyChar.
Allow the user to enter real numbers:
int num1 = int.Parse(Console.ReadLine());
Focus on error handling and the switch statement in version 2 of your program.
Because when you enter 2 its represented as a char which its value is 229.

Categories