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

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);

Related

Write a method GetAverage() to read 3 numbers from keyboard and return their average

I have tried to write the code, for this task, but I am getting an error with my 'ReadLine'.
class Program
{
static void Main(string[] args)
{
double average = GetAverage();
Console.WriteLine("The average of the numbers is: " + average);
}
public static double GetAverage()
{
double num1 = double.Parse(Console.ReadLine("Enter the first number: "));
double num2 = double.Parse(Console.ReadLine("Enter the second number: "));
double num3 = double.Parse(Console.ReadLine("Enter the third number: "));
return (num1 + num2 + num3) / 3;
}
}
The Console.ReadLine() does not accept any argument. It read data from the console and return an string.
You should use Console.WriteLine for printing data on console screen and use Console.ReadLine to getting data from console :
public static double GetAverage()
{
Console.WriteLine("Enter the first number: ");
double num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number: ");
double num2 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the third number: ");
double num3 = double.Parse(Console.ReadLine());
return (num1 + num2 + num3) / 3;
}

How to prompt the user to continue?

I want to ask the user if they want to continue adding two numbers, so if they type Y it would start again if N it will exit.
I'm not sure if I should use if/else or while (or both!) or something else.
Here is what I have so far:
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.Write("Do You want to add more numbers? Y / N");
Console.ReadLine();
How can I finish it?
First, let's extract method ReadInt (why should you repeat yourself?):
private static int ReadInt(string title) {
// keep asking user until correct value provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
// If we can parse user input as integer...
if (int.TryParse(Console.ReadLine(), out int result))
return result; // .. we return it
Console.WriteLine("Syntax error. Please, try again");
}
}
Main code: Here, you can wrap the code fragment into do {...} while (since you want the loop to be performed at least once)
do {
int num1 = ReadInt("Enter a number to add: ");
int num2 = ReadInt("Enter another number to add: ");
// (long) num1 - we prevent integer overflow (if num1 and num2 are large)
Console.WriteLine($" {num1} + {num2} = {(long)num1 + num2}");
Console.WriteLine("Do You want to add more numbers? Y / N");
}
while(Console.ReadKey().Key == ConsoleKey.Y);
while (true)
{
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.WriteLine("Do You want to add more numbers? Y / N");
string YesOrNo = Console.ReadLine();
if (YesOrNo == "N")
{
break;
}
}
You need a loop the most common that I see for a scenario like this is the while loop. You also however need a break condition so that the while loop ends an if statement is one way you could break out like in my example above. The break is reached if the user enters N into the console.
Note my example will continue to run if anything other than N is typed into the console.

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;
}
}
}
}

Code is working unexpectedly in c# using visual studio code

I am a beginner in c# and I want to create a simple calculator.
I have written all the code and it is not showing any errors, however, it is not showing it correctly.
This is all the code I am using:
using System;
namespace C_
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Calculator";
float num1;
float num2;
float resultSum;
float resultSub;
float resultProd;
float resultDiv;
Console.Write("Enter your first number ");
num1 = Convert.ToInt32(Console.Read());
num2 = Convert.ToInt32(Console.Read());
resultSum = num1 + num2;
Console.Write("The sum is " + resultSum);
resultSub = num1 - num2;
Console.Write("The differnce is " + resultSub);
resultProd = num1 * num2;
Console.Write("The product is " + resultProd);
resultDiv = num1 / num2;
Console.Write("The quotient is " + resultDiv);
Console.ReadKey();
}
}
}
When I run this without debugging,
the console shows this:
https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=netcore-3.1
If you replace Console.Write... with Console.WriteLine..., it will add line breaks to the ends of your print statements, so your output should look like:
The sum is 63
The difference is 37
...
Not sure if I would use float for the type. Especially since you are converting to int32. I have put some different techniques into your program. Since you are just learning these are good things to know. I have provided explanations in the comments of the code.
static void Main(string[] args)
{
Console.Title = "Calculator";
// No need to put the type multiple times
// Just use a comma to separate the names
int num1, num2, resultSum, resultSub, resultProd, resultDiv;
Console.WriteLine("Enter your first number:");
// This is just a label
Num1Entry:
try
{
num1 = Convert.ToInt32(Console.ReadLine());
}
// This exception is for when you don't get a number from the user. i.e. num1 = a
catch (FormatException)
{
Console.WriteLine("Not a number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num1
goto Num1Entry;
}
// This exception is for when the number is out of range for the data type. i.e. num1 = 2147483648 is too big for an int data type.
catch (OverflowException)
{
Console.WriteLine("Invalid number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num1
goto Num1Entry;
}
Console.WriteLine("Enter your second number:");
// This is just a label
Num2Entry:
try
{
num2 = Convert.ToInt32(Console.ReadLine());
}
// This exception is for when you don't get a number from the user. i.e. num2 = a
catch (FormatException)
{
Console.WriteLine("Not a number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num2
goto Num2Entry;
}
// This exception is for when the number is out of range for the data type. i.e. num2 = 2147483648 is too big for an int data type.
catch (OverflowException)
{
Console.WriteLine("Invalid number. Please enter a valid number.");
// This will jump your program back to the beginning of the try-catch so you can enter a valid number for num2
goto Num2Entry;
}
resultSum = num1 + num2;
Console.WriteLine("The sum is " + resultSum);
resultSub = num1 - num2;
Console.WriteLine("The differnce is " + resultSub);
resultProd = num1 * num2;
Console.WriteLine("The product is " + resultProd);
// if num2 = 0 you will get an exception.
// Use a try-catch to keep your program from failing.
try
{
resultDiv = num1 / num2;
Console.WriteLine("The quotient is " + resultDiv);
}
catch (DivideByZeroException)
{
Console.WriteLine("You cannot divide by 0");
}
Console.ReadKey();
}
Your code uses the consolekey values, not the numeric value that you entered. The consolekey for 2 is 50. The consolekey for return is 13.

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

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();
}
}
}

Categories