Getting an System.FormatException in C# - c#

I am new so I don't know why I am getting such an exception and also I don't know how to explain so here is the code
using System;
namespace math
{
class Math
{
int add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Math math = new Math();
int result = 0;
for (int i = 0; i < args.Length; i++)
{
switch(args[i])
{
case "+":
result = math.add(int.Parse(args[i--]), int.Parse(args[i++]));
break;
default:
break;
}
}
Console.WriteLine(result);
Console.ReadLine();
}
}
}
this is the whole exception from VS Code
Exception has occurred: CLR/System.FormatException
An unhandled exception of type 'System.FormatException' occurred in System.Private.CoreLib.dll: 'Input string was not in a correct format.'
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Int32.Parse(String s)
at math.Math.Main(String[] args) in D:\tmp\math\Program.cs:line 20
Edit : This is a command line program like "whoami" or like "g++"?

You are modifying your loop index here:
result = math.add(int.Parse(args[i--]), int.Parse(args[i++]));
This will result in you reading the "+" again rather than the numbers you're expecting, which is why you're getting the FormatException.
Change the line to:
result = math.add(int.Parse(args[i - 1]), int.Parse(args[i + 1]));
This is easier to understand and doesn't mess with the loop index.
This will still fail if someone enters "a + b" (say), so you should really check that the values are integers:
int first;
int second;
if (int.TryParse(args[i-1], out first) &&
int.TryParse(args[i+1], out second))
{
result = first + second;
}
else
{
// Error: both values need to be numeric
}

Following would be an simple alternative to start with if it is C#.
class Math
{
int add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Math math = new Math();
Console.Write("Enter Integer: ");
var val1 = Console.ReadLine();
int a = Convert.ToInt32(val1);
Console.Write("Enter Integer: ");
var val2 = Console.ReadLine();
int b = Convert.ToInt32(val2);
Console.Write("Enter Operation: ");
var operation = Console.ReadLine();
int result = 0;
switch(operation)
{
case "+":
result = math.add(a, b);
break;
default:
break;
}
Console.WriteLine(result);
Console.ReadLine();
}
}

Related

C# Console Calculator with all input on a one line

I am trying to make a program that is a small console calculator where the input is inserted on a single line in the console. example the input "88+12*7/2" should be translated into a math operation looking like this => "((88+ 12) * 7)/2" and print answer in the console.
I will be grateful if you help me to complete this code...
I did a part of the project but it only works to do the operator on two numbers
static string Input_User()
{
string Input_User = Console.ReadLine();
return Input_User;
}
static void ShowMessage()
{
Console.WriteLine("Enter your numbers with operation like: 7*7");
}
ShowMessage();
string input_string = Input_User();
int result = PerformCalculation(InputToList(input_string));
Console.WriteLine($"{input_string}={result}");
static string[] InputToList(string input)
{
string number1 = "";
string number2 = "";
string Oprt = "";
string[] Arithmetic = new string[3];
int n = 0;
foreach (char charecter in input)
{
int num;
bool isNumerical = int.TryParse(charecter.ToString(), out num);
n += 1;
if (isNumerical)
{
number1 += num;
}
else
{
Oprt = charecter.ToString();
Arithmetic[0] = number1;
Arithmetic[1] = Oprt;
for (int i = n; i <= input.Length - 1; i++)
{
number2 += input[i];
}
Arithmetic[2] = number2;
}
}
return Arithmetic;
}
static int PerformCalculation(string[] Input)
{
int result = 0;
switch (Input[1])
{
case "+":
result = Int32.Parse(Input[0]) + Int32.Parse(Input[2]);
break;
case "-":
result = Int32.Parse(Input[0]) - Int32.Parse(Input[2]);
break;
case "*":
result = Int32.Parse(Input[0]) * Int32.Parse(Input[2]);
break;
case "/":
result = Int32.Parse(Input[0]) / Int32.Parse(Input[2]);
break;
}
return result;
}
If your input would be for example '5 + 5 + 5' it would not work because your function InputToList would do the following
InputToList("5+5+5")
-> Return Value ["5","+","5+5"]
The function PerformCalculation would now try to parse 5+5 to an Integer, and that's simply not possible.
One Solution would be to use regular expressions to filter and check the input.
Then you could use a binary tree or a linked list in which you insert the numbers and operators.
After this you would be able to iterate over the list/tree and to do multiple operations.

C# re-enter value after wrong input instead of restarting the program

so I am trying to make a multiplication table with c#, and I want that when user give a wrong input in code it should not start the program from start but just ask to re-enter that value. when I run this code and put wrong input. it will ask to display the multiplication table again. but I want that if I give wrong input at "start value" then it will only ask for re-entering the start value but not the whole input
public void Multi()
{
Console.Write("\n\n");
bool tryAgain = true;
while (tryAgain)
{
try
{
Console.Write("Display the multiplication table:\n ");
int t = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine(" Start value ");
Console.WriteLine("\n");
Console.WriteLine(" End value \n");
int end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
SwapNum(ref start, ref end);
Console.Write("\n");
Console.WriteLine("Display the table\n");
int i = start;
do
{
Console.WriteLine(t + " * " + i + " = " + t * i);
//Console.WriteLine("{0} * {1} = {2}", t, i, t*i);
i++;
} while (i <= end);
}
catch (Exception ex)
{
Console.WriteLine("Please Enter the inter number ");
}
}
}
static void SwapNum(ref int x, ref int y)
{
if (x >= y)
{
int temp = x;
x = y;
y = temp;
}
}
Change Parse into TryParse; let's extract a method for this
private static int ReadInt(string prompt) {
while (true) {
Console.WriteLine(prompt);
int result;
if (int.TryParse(Console.ReadLine(), out result))
return result;
Console.WriteLine("Sorry, it's not a correct integer value, please try again.");
}
}
...
public void Multi() {
Console.Write("Display the multiplication table:\n ");
// Now we keep asking user until the correct value entered
int t = ReadInt("Start value");
...
}

C# converting strings to int's

I'm new to c# and am trying to make a simple calculator.
It works fine until it goes back to the start to take a new number.
When taking the new number it says it cant convert the user input to a integer.
using System;
namespace simpleCalculator
{
class MainClass
{
public static void Main(string[] args)
{
start:
Console.Clear();
Console.WriteLine("Enter first number");
int x = Convert.ToConsole.ReadLine();
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Devide");
string o = Console.ReadLine();
if (o == "1")
{
Console.WriteLine("Enter second number\n");
int y = Convert.ToInt32(Console.ReadLine());
add(temp, y);
goto start;
Console.Clear();
goto start;
}
}
public static void add(int num01, int num02)
{
Console.Clear();
Console.WriteLine((num01 + num02) + "\nPress enter to contiue.");
Console.Read();
}
}
}
Use TryParse so if the parsing fails, you will not get an exception.
var enteredValue = Console.ReadLine();
var parsedValue;
if (!int.TryParse(enteredValue, out parsedValue))
{
// parse failed do whatever you want
}
Do that for both entries and if both of them pass, then call your add method.
You're looking for int.Parse(). Be careful to validate your input. You should probably create an escape condition.
Edited to show an alternative solution
Edited to be more explicit on how to handle some input
class Program
{
public static void Main(string[] args)
{
string input = String.Empty;
int x = 0, y = 0;
while (true)
{
try
{
Console.WriteLine("Enter first number");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Divide");
input = Console.ReadLine();
Console.WriteLine("Please enter a second number");
y = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
continue;
}
switch (input)
{
case "1":
Console.WriteLine($"{x} + {y} = " + add(x, y));
break;
case "2":
//TODO implement multiply case
break;
case "3":
//TODO implement divide case
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
}
public static int add(int x, int y) => x + y;
}
Try this:
int numbers = Convert.ToInt32("1234");

i want to restrict user to just enter integers should give error in C#and if user enters any alphabet or string characters it

i want to restrict user to just enter integers and if user enters any alphabet or string characters it should display error in c#
Console.WriteLine("enter a");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("enter b");
int b = int.Parse(Console.ReadLine());
Program e = new Program();
int sum= e.sum( a, b);
Console.WriteLine("sum is " + sum);
public int sum(int a, int b)
{
int sum = a + b;
return sum;
}
use this only if you want to check condition for integer
string strValue = Convet.toString("YourValue");
if(int.TryParse(strValue , out value))
{
}
else
{
//Value is Not Integer.
}
string a = Console.ReadLine();
string b = Console.ReadLine();
int inputnumber1 = 0;
int inputnumber2= 0;
if (int.TryParse(a,out inputnumber1))
{
}
like that
you can do a try catch:
try
{
Console.WriteLine("enter a");
string a = Console.ReadLine();
Console.WriteLine("enter b");
string b = Console.ReadLine();
a=int.parse(a);
b=int.parse(b);
Program e = new Program();
int sum= e.sum( a, b);
Console.WriteLine("sum is " + sum);
public int sum(int a, int b)
{
int sum = a + b;
return sum;
}
}
catch(FormatException e){Console.WriteLine("Wrong input");}
or you can also do something like this to get the user input and repeat the ask to get the parameters if it fails:
Boolean wrongInput=true;
string read;
int a;int b;
while(wrongInput)
{
Console.WriteLine("enter a");
read = Console.ReadLine();
bool isNumeric = int.TryParse(read, out a);
if(isNumeric){wrongInput=false;}
}
wronginput=while(wrongInput)
{
Console.WriteLine("enter b");
read = Console.ReadLine();
bool isNumeric = int.TryParse(read, out b);
if(isNumeric){wrongInput=false;}
}
You could do a check before you parse the input to int.
string input = Console.Readline();
if(IsInt(input))
int a = int.Parse(input);
else
//Error message here
private bool IsInt(string in)
{
string intChars = "0123456789";
return in.All(intChars.Contains);
}
Another option would be to use int.TryParse(), see https://msdn.microsoft.com/de-de/library/f02979c7(v=vs.110).aspx on that.

Is there a more elegant way to read the numbers from the input stream?

I have the following test-client code in Java:
public static void main(String[] args)
{
int N = StdIn.readInt(); // Read number of sites.
while (!StdIn.isEmpty())
{
int p = StdIn.readInt();
int q = StdIn.readInt();
}
}
And in C#:
public static void Main(string[] args)
{
int N = Convert.ToInt32(Console.ReadLine());
string input;
while ((input = Console.ReadLine()) != null)
{
int p = Convert.ToInt32(input);
int q = Convert.ToInt32(Console.ReadLine());
}
}
I'm new in C#. Please, help me, is there a more elegant way to read the numbers from the input stream ? For example, how to simulate while (!StdIn.isEmpty()) more accurately in C# ?
I'd recommend to use TryParse method rather than Convert.ToInt32 because it doesn't throw System.FormatException when failed to convert. It also returns the bool result of the conversion operation.
IsNullOrWhiteSpace is somewhat 'more elegant' way to check the string value :
int n, p, q;
string input;
Int32.TryParse(Console.ReadLine(), out n);
while (!string.IsNullOrWhiteSpace((input = Console.ReadLine())))
{
Int32.TryParse(input, out p);
Int32.TryParse(Console.ReadLine(), out q);
}
Console.ReadKey();

Categories