Code is working unexpectedly in c# using visual studio code - c#

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.

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.

if-statement inside a try-catch block returns "Infinite"

First of all i'm new to programming and just finished the Course on SoloLearn about C#.
I do understand the core principal of try-catch blocks but i can't figure out how to correctly implement this in to my code(code shown below).
class Program
{
static void Main(string[] args)
{ //create object of Class Calculator
Calculator calc = new Calculator();
//take user input and store in num1 and print it to screen
try{
double num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nnumber1: " + num1);
double num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nnumber2: " + num2);
//take operator as input and print it to screen
string operand = Console.ReadLine();
Console.Write("\noperator: " + operand);
//check if operator from user input is equal to one of the 4 calculation methods in Calculator Class
Console.Write("\nresult: ");
if(operand == "+"){
Console.WriteLine(calc.Addition(num1, num2));
}
else if(operand == "-"){
Console.WriteLine(calc.Subtraction(num1, num2));
}
else if(operand == "*"){
Console.WriteLine(calc.Multiplication(num1, num2));
}
else{
Console.WriteLine(calc.Division(num1, num2));
}
}
catch(DivideByZeroException){
Console.WriteLine("can't divide by zero");
}
catch(Exception e){
Console.WriteLine("An error occurred. Only integers are allowed!");
}
}
}//class Calculator with methods for 4 simple calculations
class Calculator{
private double number1;
private double number2;
private double res;
public double Addition(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 + num2;
return res;
}
public double Subtraction(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 - num2;
return res;
}
public double Multiplication(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 * num2;
return res;
}
public double Division(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 / num2;
return res;
}
}
So i want my simple calculator to handle the exception "DivideByZero" and "Exception e" -> if the input was not an integer.
When i test the DivideByZero Exception with an example input of 4/0, the programm returns "Infinite" as a result instead of the code from the catch block.
I guess the "Infinite" result comes from the if-statements inside the try-catch block but i'm not sure.
I searched multiple sites, similar posts on stackoverflow and read the microsoft documentation for c# about try-catch blocks but i just can't figure it out.
Sorry if my code sample is too big but i think this is the best way to understand my mess of code.
Thank you in advance for the quick reply !
Change fragment
else {
Console.WriteLine(calc.Division(num1, num2));
}
into
else {
Console.WriteLine(num2 != 0
? $"{calc.Division(num1, num2)}"
: "can't divide by zero");
}
Since floating point division doesn't throw exception but returns NaN, PositiveInfinity and NegativeInfinity:
0.0 / 0.0 == double.NaN
1.0 / 0.0 == double.PositiveInifinity
-1.0 / 0.0 == double.NegativeInfinity
There is nothing wrong with your try catch. If you divide a double by zero, you don't get an exception. You get Double.PositiveInfinity as result in your case.
The DivideByZeroException is only thrown for integer or decimal data types.

how do I write in the same line that the user wrote?

The user enters a numbers and the program should make a sideways graph by writing "-" * the amount of digits in the number, but it writes the "-" a line under the user input
Current output:
Expected output:
static void Main(string[] args)
{
int num1, num2;
Console.WriteLine("how many numbers will you want to enter?");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter " + num1 + " numbers");
for(; num1 > 0; num1--)
{
num2 = int.Parse(Console.ReadLine());
Hi(num2);
}
}
static void Hi(int num)
{
while(num != 0)
{
num /= 10;
Console.Write("-");
}
Console.WriteLine()
}
You can get and set the cursor position in the console, so if you remember which line it is on before the user presses enter for the number entry, you can put the cursor back on that line.
Also, to print a number of dashes of the length of the input, it is not necessary for the input to be digits (or you would have checked for that).
Something like this should be suitable:
static void Main(string[] args)
{
Console.Write("How many numbers will you want to enter? ");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter " + num1 + " numbers");
for (; num1 > 0; num1--)
{
int currentLine = Console.CursorTop;
string num2 = Console.ReadLine();
Console.SetCursorPosition(20, currentLine);
Console.WriteLine(new string('-', num2.Length));
}
Console.WriteLine("\r\n(Press enter to leave program.)");
Console.ReadLine();
}
Sample output:
How many numbers will you want to enter? 4
Enter 4 numbers
1 -
435 ---
What happens long wi-----------------------
(Press enter to leave program.)
Use a method like the following:
public string getKeyBuffer()
{
string buffer = "";
do
{
var charIn = Console.ReadKey(true);
if (charIn.Key == ConsoleKey.Enter) break;
buffer += charIn.KeyChar;
Console.Write(charIn.KeyChar);
} while (true);
return buffer;
}
This will echo each key pressed and then return all the keys pressed once the user presses the enter key without echoing the enter key.
The best solution would be to write to something other than the console, where you would have absolute control over what is displayed and where.
Another solution would be to format a string in your code, then clear the console and write the entire thing each time.
Another solution would be to keep track of where you are and move the console cursor using Console.SetCursorPosition. However, this is rarely a satisfying solution given the existence of nicer output alternatives.
You can move the cursor up one line with Console.CursorTop--;, avoiding the necessity of keeping track of which line you are on.

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