Can someone explain to me what's wrong with my code please? - c#

I've been learning C# and now I'm trying to create a calculator that reads your inputs to learn how to read inputs correctly. If it's really simple I'm sorry I'm new to this.
The error says that it can't convert int to string on (10,20) and (14,20).
using System;
class Calculator {
static void Main() {
int n1, n2;
string operation;
Console.Write("First number: ");
n1 = int.Parse(Console.Read());
Console.Write("Operation: ");
operation = Console.ReadLine();
Console.Write("Second number: ");
n2 = int.Parse(Console.Read());
if (operation == "+") {
Console.Write(n1 + n2);
}else if (operation == "-") {
Console.Write(n1 - n2);
}else if (operation == "*") {
Console.Write(n1 * n2);
}else if (operation == "/") {
Console.Write(n1 / n2);
};
}
} ```

Make all your calls Console.ReadLine() not Console.Read()
Make sure you type an integer for the operands. If you're not typing an integer (I couldn't decide if your 10,20 means your operands are ten and twenty or if you're from a country that uses comma as a decimal separator and 10,20 is ten-and-a-fifth) then you won't succeed in parsing a decimal number with int.Parse, try decimal.Parse instead and change all your data types
Using Console.Read() will read a single character and return its numeric value, so eg a 1 character has an int value of 31 (take a look at an ascii table) which will be very confusing, and even more confusing how A (ascii Value 65) can be added to B (66 - result 131) :) ...

Try with dot. 10.20 and 14.20.
Also try ReadLine

Try this as a starter for 10. There are ways to do it more efficiently I'm sure, but this should give you some ideas:
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
Console.Write("First Number: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Operation: ");
string operation = Console.ReadLine();
Console.Write("Second number: ");
int b = int.Parse(Console.ReadLine());
switch(operation)
{
case "+":
Console.WriteLine(string.Format("Result: {0}", (a + b)));
break;
case "-":
Console.WriteLine(string.Format("Result: {0}", (a - b)));
break;
case "*":
Console.WriteLine(string.Format("Result: {0}", (a * b)));
break;
case "/":
Console.WriteLine(string.Format("Result: {0}", (a / b)));
break;
}
Console.WriteLine("Press any key to close...");
Console.ReadKey();
}
}
}

Related

How would i allow the user to input a symbol like "+" or "-" and allow that to be used in a calculation in C#

using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("would you like to Subtract(-), add(+), multiply(*) or divide(/), you must enter a symbole or it will not work");
string symbol = Console.ReadLine();
Console.Write("Enter your second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
}
}
}
I want it to use the user input of either +, -, / or * to add the numbers the user has chosen
You could use a string and from there write your own code that looks for operators and do the expected calculation.
You could use a switch statement to select the right operation. Don't make it too complex. You'll need to add some code such as trimming. For example instead of '+', you'll enter '+ '
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("would you like to Subtract(-), add(+), multiply(*) or divide(/), you must enter a symbole or it will not work");
string symbol = Console.ReadLine();
Console.Write("Enter your second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
switch (symbol)
{
case "+":
Console.Write($"The anser is {num1 + num2}");
break;
case "-":
Console.Write($"The anser is {num1 - num2}");
break;
case "*":
Console.Write($"The anser is {num1 * num2}");
break;
case "/":
Console.Write($"The anser is {num1 / num2}");
break;
default:
Console.Write($"Too bad '{symbol}' is not implemented");
break;
}
}
}
}

I can't figure out why my Console.ReadLine() is not working

I'm relatively new to programming and I'm working on various projects to get better at it. One is a calculator that I want to be able to solve more than just basic addition and subtraction. Currently, all I have is the basics with the quadratic formula. But my design weighs on user input to decide what to do. It prompts the user with "What would you like to do? Add: Sub: Div: Mul: Quad Equation:" After typic in "Add" the code operates normally but if I type in anything else like "Sub" or "Div". it does nothing. doesn't even spit back an error. As far as I can tell, my code is fine (well it's terrible code but it should work nonetheless) But I just do not know how to proceed.
using System;
namespace Better_Calculator
{
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
double a;
double b;
double c;
System.Console.WriteLine("Welcome to how you are going to cheat through math lol");
System.Console.WriteLine("What would you like to do? \nAdd: \nSub: \nDiv: \nMul: \nQuad Equation: ");
if (Console.ReadLine() == "Add")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Add(num01, num02);
}
else if (System.Console.ReadLine() == "Sub")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Sub(num01, num02);
}
else if (System.Console.ReadLine() == "Mul")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Mul(num01, num02);
}
else if (System.Console.ReadLine() == "Div")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Div(num01, num02);
}
else if (System.Console.ReadLine() == "Quad Equation")
{
System.Console.WriteLine("what is a?");
a = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is b");
b = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is c");
c = Convert.ToInt32(Console.ReadLine());
Quad(a, b, c);
}
static void Add(double num01, double num02)
{
string answer = Convert.ToString(num01 + num02);
System.Console.WriteLine(answer);
}
static void Sub(double num01, double num02)
{
string answer = Convert.ToString(num01 - num02);
System.Console.WriteLine(answer);
}
static void Mul(double num01, double num02)
{
string answer = Convert.ToString(num01 * num02);
System.Console.WriteLine(answer);
}
static void Div(double num01, double num02)
{
string answer = Convert.ToString(num01 / num02);
System.Console.WriteLine(answer);
}
static void Quad(double a, double b, double c)
{
double bNeg = b * -1;
double bSqr = b * b;
double SqR = Math.Sqrt(bSqr - (4 * a * c));
double solvedAdd = (bNeg + SqR) / (2 * a);
double solvedSub = (bNeg - SqR) / (2 * a);
string answer = Convert.ToString(solvedAdd) + " or " + Convert.ToString(solvedSub);
System.Console.WriteLine(answer);
}
}
}
}
With every ´if´, you call Console.ReadLine() again, so if you enter "Quad Equation", your code has passed 5 Readlines until you reach the code that does Quad Equation.
Solution: Do only one Console.ReadLine() and put its result into a variable:
var userInput = Console.ReadLine();
and then, test against userInput in your if statements (ex.)e:
else if (userInput == "Sub")
You only need to do a ReadLine once and store the value, then use that to compare. For example:
var operation = Console.ReadLine();
if(operation == "Add")
{
// Do add stuff
}
But you should consider using a switch statement instead:
switch(operation)
{
case "Add":
// do Add Stuff
break;
case "Sub":
// do Add Stuff
break;
case "Mul":
// do Add Stuff
break;
// etc...
}
When we get input from console application from user may be they given as
CAPS, Small or combination of both
. In that situation you can use the following approach,
string value=Console.ReadLine();
if(string.Equals(value, "Add", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}
else if(string.Equals(value, "Sub", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}

C# FormatException error [duplicate]

I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong? I am supposed to make this console program as homework to learn about loops, but I am finding out more about other things. It is supposed to keep a running tab of salesperson's commission based a a 10% commission of each sale. Anyways, here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TubSales
{
class Program
{
static void Main(string[] args)
{
char initial;
const double COMM_INT = 0.10;
double sale, aComm = 0, bComm = 0, eComm = 0;
Console.Write("Enter 'A' for Andrea, 'B' for Brittany,\n'E' for Eric, or 'Z' to quit >> ");
initial = Convert.ToChar(Console.Read());
while (initial != 'z' && initial != 'Z')
{
switch (initial)
{
case 'a':
case 'A':
Console.Write("Enter the sales for Andrea >> ");
sale = Convert.ToDouble(Console.ReadLine());
aComm = aComm + COMM_INT * sale;
break;
case 'b':
case 'B':
Console.Write("Enter the sales for Brittany >> ");
sale = Convert.ToDouble(Console.ReadLine());
bComm = bComm + COMM_INT * sale;
break;
case 'e':
case 'E':
Console.Write("Enter the sales for Eric >> ");
sale = Convert.ToDouble(Console.ReadLine());
eComm = eComm + COMM_INT * sale;
break;
default:
Console.WriteLine("You did not enter a valid initial");
break;
}
Console.Write("Enter 'A' for Andrea, 'B' for Brittany, or 'E' for Eric >> ");
initial = (char)Console.Read();
}
Console.WriteLine("Andrea had {0}, Brittany had {1}, and Eric had {2} in commissions.", aComm.ToString("C"), bComm.ToString("C"), eComm.ToString("C"));
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
}
}
I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong?
The Convert.ToDouble method will raise a FormatException if the string (returned from Console.ReadLine()) is not a valid number.
Typically, if you want to parse user input, it's a better idea to use Double.TryParse instead, as this lets you determine whether the input was a valid number without catching the exception.
This would normally look something like:
Console.Write("Enter the sales for Andrea >> ");
while (!double.TryParse(Console.ReadLine(), out sale))
{
Console.WriteLine("Value entered was not a valid number.");
Console.Write("Enter the sales for Andrea >> ");
}
// Once you get here, "sale" will be set appropriately
While Reed's answers is great, it's not the problem here.
What really happens is the same situation as this one
Console.Read only read the "Second part of the carriage return" and returns "". This is why the Convert fails.
replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine());
Replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());

simple temperature conversion questions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConTempConversion_LeeMichelle
{
class Program
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
Console.Write("Enter choice: ");
Console.ReadKey();
int ichoice = 0;
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.ReadKey();
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
Console.ReadKey();
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice > 3);
Console.ReadKey();
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
}
so suppose the user has three options from 1 - 3. After option 3, there will be an error alert. my problem is why this code gives me an infinity loop? what did I do wrong? can I put break after each if statment?
Please help, thank you!
You're creating a do...while loop without anything to ever exit it. When the loop begins, ichoice is already set in stone. So you'll always be stuck in that loop!
You are never assigning a value to ichoice If I were you, I would try something like this:
int ichoice = 0;
int.TryParse(Console.ReadKey().ToString(), out ichoice );
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
Add the int.TryParse(Console.ReadKey().ToString(), out ichoice ); everywhere you have Console.Readline(). What this is doing is getting the user input and converting it to an integer (if it's not an integer, then the value is 0).
Also add this:
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
break;
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
}
Finally, remove this (I'm not quite sure what it was for...)
while (ichoice > 3);
Console.ReadKey();
When you need to do some prep work before your condition, the most straightforward way involves combining your loop with a separate structure.
This is the format to use when your loop condition is at the beginning of the loop:
prep work
while (condition) // if false then loop body will never run
{
loop body
}
This is the format to use when the loop condition is at the end of the loop:
prep work
do
{
loop body
}
while (condition); // loop body will always execute at least once
In this case, you have some prep work to do before each iteration--you want to get the key press from the user each time. For this, I recommend the following from Code Complete:
while (true) // loop termination condition is inside the loop
{
prep work
if (condition)
{
break;
}
loop body
}
In your case, it would look something like:
Console.Write("Enter choice: ");
while (true) // loop termination condition is inside the loop
{
Console.ReadKey();
if (ichoice == 3)
{
Console.WriteLine(...);
break;
}
...
}
Also, consider changing most of your ifs into else ifs; otherwise, you're repeatedly checking the condition even when you've gone through one case.
you should assign a value to iChoice. and set your while to read a terminating character. like:
namespace YourNameSpace
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
int iChoice;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
do{
switch(iChoice)
{
case 1:
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
case 2:
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
}
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
}while(iChoice != 0);
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
Each time you call Console.ReadKey you should store returning value.You are receiving input from user but you didn't store it anywhere.
First you can create a function to get ichoice, and force user to enter the correct value:
static void GetChoice(ref int ichoice)
{
string input = Console.ReadLine();
Console.Write("Enter choice: ");
bool result = int.TryParse(input, out ichoice);
if (!result)
{
while (!result && ichoice > 3)
{
Console.WriteLine("Invalid value.Try again:");
input = Console.ReadLine();
result = int.TryParse(input, out ichoice);
}
}
}
Then use this function whenever you need to make a choice.
Here is the working version or your program:
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
int ichoice = 0;
GetChoice(ref ichoice);
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
Console.WriteLine(cTemp + "Celsius is " + cTemp + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice < 3);
}
static double ConvertCelcius(double c)
{
double f;
return f = 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f)
{
double c;
return c = 5.0 / 9.0 * (f - 32);
}
And here is the full code: http://pastebin.com/bkegSAFL

C# adding methods and checking to see if numbers have been added

have a small program im playing with. need to make sure it checks if number, if not loop untill their is a number on each input and create a main method and calculator method any help?
code is here /////////////////////////////////////////////////////
int num1;
int num2;
string operand;
float answer;
string text1;
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
// if number not integer then fail ////
bool res = int.TryParse(text1, out num1);
if (!res)
{
Console.WriteLine(" FAIL");
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
}
else
{
}
//// enter operand ////
Console.Write("Please enter an operand (+, -, /, *): ");
operand = Console.ReadLine();
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
// if number not integer then fail //
bool eff = int.TryParse(text1, out num2);
if (!eff)
do
{
Console.WriteLine(" FAIL");
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
}
while (eff == true);
{
}
// converts number to integer ///
// makes operand answers from each number ////
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " =
"+ answer.ToString());
Console.ReadLine();
}
}
}
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " =
" + answer.ToString());
Console.ReadLine();
If this is all you need and you are using a Console App, you can use:
int num1;
int num2;
string operand = string.Empty;
float answer;
string text1;
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
// if number not integer then fail ////
bool res = int.TryParse(text1, out num1);
while (!res)
{
Console.WriteLine(" FAIL");
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
res = int.TryParse(text1, out num1);
}
//// enter operand ////
while (operand == string.Empty || operand.Length > 1 || !(new char[] { '+', '-', '*', '/' }).Contains(char.Parse(operand)))
{
Console.Write("Please enter an operand (+, -, /, *): ");
operand = Console.ReadLine();
}
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
// if number not integer then fail //
bool eff = int.TryParse(text1, out num2);
while (!eff)
{
Console.WriteLine(" FAIL");
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
eff = int.TryParse(text1, out num2);
}
// converts number to integer ///
// makes operand answers from each number ////
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Divide By Zero Error");
return;
}
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " = "+ answer.ToString());
Console.ReadLine();
Why do you need to create a separate method for something so simple. And I found this too simple to be asked, so just asking if this is what was required? You could have struggled a bit more and written this yourself. There is nothing trivial in this. I am just assuming that you are new to programming.
the problem appears to be with the handling of "eff" and "res". If the user keys a non integer value the first time they're asked it doesn't matter what they answer the second time as num1 and num2 aren't populated with the value. Fix that and the code appears to work.
As entering the values appears to be doing the same thing but with a slightly different prompt you should move this into a seperate function, something like this:
static int GetNumberFromUser(string order)
{
string userText = String.Empty;
int result;
Console.Write("Please enter {0} number: ", order);
userText = Console.ReadLine();
while (!int.TryParse(userText, out result))
{
Console.WriteLine("FAILED");
Console.Write("Please enter {0} number: ", order);
userText = Console.ReadLine();
}
return result;
}
You would then call it by calling
num1 = GetNumberFromUser("first");
num2 = GetNumberFromUser("second");
This function takes care of converting to a number and keeps asking until the user keys in a valid value.
The "Calculator" method would just be copied and pasting the switch you have into a seperate method:
static float Calculator(int num1, string operand, int num2)
{
switch (operand)
{
case "-":
return num1 - num2;
case "+":
return num1 + num2;
case "/":
return num1 / num2;
case "*":
return num1 * num2;
default:
return 0;
}
}
Called using
answer = Calculator(num1, operand, num2);
Whilst I'm at it, the result line is difficult to read, I'd go for something like this
Console.WriteLine("{0} {1} {2} = {3}", num1, operand, num2, answer);

Categories