C# converting strings to int's - c#

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

Related

Restarting a program after error in catch statement

I'm trying to restart my program after I catch an error using the catch() function, but I also want it to display the error, stop the rest of the program from running, and restart the program.
This is just a shortened version of my code which I have used as an example.
using System;
namespace Calculator
{
internal class Program
{
private static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}
When it says
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
The break; makes it so the rest of the code stops, and it displays the error. That is good, but the program also ends after that, what I want, is that the program repeats after error. Is there any way that this could happen, but it allows 1) the Console.WriteLine("Please enter a number");, 2) the program to not run the rest of the code (The part where we are asked for a second value), and 3) the program to restart for the beginning. Please let me know if that didn't make sense, as it was a hard to explain. :)
It is very simple you do not need the "break" keyword because "break" terminates the loop execution to continue execution on exception use "continue" keyword without quotes the working fiddle is here
and your code after replacing "break" with "continue" is following
using System;
namespace Calculator
{
public class Program
{
public static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}

Getting an System.FormatException in 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();
}
}

goto - not within scope (C#)

I am very new to code. Can anyone in a simple way explain why I cant use the goto statement like this, to make the code start over again? Or, how this could have been done in the correct way? And also, why I get an error message on the use of "static".
**
"No such label "Start" within the scope of the goto statmenet"
"The modifier static is not valid for this item"
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Start:
Random numberGenerator = new Random();
int num1 = numberGenerator.Next(1,11);
int num2 = numberGenerator.Next(1, 4);
Console.WriteLine("What is " + num1 + " times " + num2 + "?");
int svar = Convert.ToInt32(Console.ReadLine());
if (svar == num1 * num2)
{
Console.WriteLine("well done!");
}
else
{
int responseIndex = numberGenerator.Next(1, 4);
switch (responseIndex)
{
case 1:
Console.WriteLine("Wrong, try again? [Y or N]");
AskUser();
break;
case 2:
Console.WriteLine("The answer was incorrect");
AskUser();
break;
default:
Console.WriteLine("You can do better than that");
AskUser();
break;
}
static void AskUser() {
string jaellernei = Console.ReadLine().ToUpper();
if (jaellernei == "Y")
{
goto Start;
} else
{
return;
} }
}
}
}
}
Firstly, your AskUser method is incorrectly nested inside the other method - move it out.
Secondly: goto is only valid within a single method; you can jump around a single stack frame - you cannot jump between stack frames.
Thirdly: the number of times you should be using goto... well, it isn't quite zero, but it asymptotically approaches zero.
Don't use goto unless you MUST to !
and As #Marc Gravell said, it's valid within a single method.
Alternatively : you can make a method of the code u used in the Main method, and then call it from both, main method and the other method where you used goto statement.
Like :
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
someFunction();
}
static void someFunction()
{
Random numberGenerator = new Random();
int num1 = numberGenerator.Next(1, 11);
int num2 = numberGenerator.Next(1, 4);
Console.WriteLine("What is " + num1 + " times " + num2 + "?");
int svar = Convert.ToInt32(Console.ReadLine());
if (svar == num1 * num2)
{
Console.WriteLine("well done!");
}
else
{
int responseIndex = numberGenerator.Next(1, 4);
switch (responseIndex)
{
case 1:
Console.WriteLine("Wrong, try again? [Y or N]");
AskUser();
break;
case 2:
Console.WriteLine("The answer was incorrect");
AskUser();
break;
default:
Console.WriteLine("You can do better than that");
AskUser();
break;
}
}
}
static void AskUser()
{
string jaellernei = Console.ReadLine().ToUpper();
if (jaellernei == "Y")
{
someFunction();
}
else
{
return;
}
}
}
}
You could do it like this
public static Random randd = new Random();
public static void FlachCards()
{
Start:
if (AskAUser() == "Y")
{
goto Start;
}
}
public static String AskAUser()
{
Console.WriteLine("Enter Y to play again");
return Console.ReadLine();
}

checking integers in String

I'm checking a string whether it has integers or anything else in function Parse().
Here is my Code
static public int input()
{
Console.WriteLine("Enter The Number Of Student You Want to get Record");
int x;
string inputString = Console.ReadLine();
if (int.TryParse(inputString, out x))
{
Console.WriteLine(inputString + " Is Integer");
return x= Convert.ToInt32(inputString);
}
else
{
input();
}
return x;
}
And full code is:
static void Main(string[] args)
{
int num = 0;
string[] names = new string[] { };
long[] fee = new long[] { };
string[] className = new string[] { };
do
{
Console.WriteLine("Enter Option You Want: \nA:Enter Student Record\nB:Display Student Record\nQ:Exit");
string option =null;
option =Console.ReadLine();
switch (option)
{
case "A":
case "a":
{
num = input();
names = new string[num];
fee = new long[num];
className = new string[num];
for (int i = 0; i < num; i++)
{
Console.WriteLine("Enter Name Of Student:{0}",i);
Console.Write("Enter Student Name: "); names[i] = Console.ReadLine();
Console.Write("Enter Student Fee: "); fee[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Student Class Name: "); className[i] = Console.ReadLine();
}
break;
}
case "B":
case "b":
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Record of Student: {0}",i);
Console.WriteLine("Name: "+names[i]+ "\nFee: " + fee[i]+ "\nClass Name: " + className[i]);
//Console.WriteLine("Name: {0}\n Class Name: {1}\n Fee: {3}\n",names[i],className[i],fee[i]);
}
break;
}
case "Q":
case "q":
{
Environment.Exit(1);
break;
}
default:
{
Console.WriteLine("Invalid Option");
break;
}
}
} while (true);
}
But The problem is when I enters char instead of int and it works fine and calls itself again but if 2nd time or after 2nd time I input int then does not take input of students and instead it repeats the LOOP again.
So what's the problem, is problem in Input Function????
You could use a regular expression to find the INTs. Also you should call
return input();
instead of
input();
new method:
static public int input(){
Console.WriteLine("Enter The Number Of Student You Want to get Record");
string input = Console.ReadLine();
if (Regex.IsMatch(input, #"\d+"))
{
return int.Parse(Regex.Match(input, #"\d+").Value);
}
else
{
return input();
}
}
I'm assuming you're a student. I started out with C# doing the same stuff. Which I wouldn't do anymore but since you are doing it. I'd recommend using goto, making this method recursive is a no no.
static public int input()
{
Prompt:
Console.WriteLine("Enter The Number Of Student You Want to get Record");
int x;
string inputString = Console.ReadLine();
if (int.TryParse(inputString, out x))
{
Console.WriteLine(inputString + " Is Integer");
return x;
}
else
{
goto Prompt;
}
}

Add numbers to array c# validating numbers only

I'm taking a C# class this semester and it has been quite fun so far. I have an assignment where I need to do several things with an array: add numbers in the array, see the numbers entered in the array, find a number in the array, sort the numbers in the array, create statistics based on the array numbers, and finally exit the application.
So far I have been having a little bit of an issue with adding numbers to the array while making sure that the data entered is only numbers. I think I am about to figure it out, but help is always appreciated. And, does my findData() method look ok?
Thank you again for your time in reading this question!
class Program
{
static char myChoice = Console.ReadKey().KeyChar;
static double[] myArray = new double[100];
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Welcome to Lab 2");
Console.WriteLine();
Console.WriteLine("Main Menu");
Console.WriteLine("1- Add new data");
Console.WriteLine("2- See all data");
Console.WriteLine("3- Find a number");
Console.WriteLine("4- Sort the data");
Console.WriteLine("5- Create statistics");
Console.WriteLine("6- Exit Program");
switch (myChoice)
{
case '1':
Console.WriteLine("1- Add new data");
addData();
break;
case '2':
Console.WriteLine("2- See all data");
seeData();
break;
case '3':
Console.WriteLine("3- Find a number");
findData();
break;
case '4':
Console.WriteLine("4- Sort the data");
sortData();
break;
case '5':
Console.WriteLine("5- Create statistics");
createData();
break;
case '6':
Console.WriteLine();
exitProgram();
break;
}
}
}
//This method will add numbers to the array
public static void addData()
{
bool isNumber = false;
double number;
double temp;
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Enter a number you would like to add");
myArray[i] = Convert.ToDouble(Console.ReadLine());
temp = myArray[i];
if (!Double.TryParse(temp, out number))
{
Console.WriteLine("Invalid input. Please enter a valid number")
}
else
{
}
}
}
//This method will see the numbers entered in the array
public static void seeData()
{
foreach (var item in myArray)
{
Console.WriteLine(item.ToString());
}
}
//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
Console.WriteLine("Find a number");
string myChoice = Console.ReadLine();
double number;
bool isNumber = Double.TryParse(myChoice, out number);
{
}
}
//This method will sort the array ascending to descending
public static void sortData()
{
Console.WriteLine("The array has been sorted in ascending order");
Array.Sort(myArray);
Console.WriteLine("The array has been sorted in descending order");
Array.Reverse(myArray);
}
//This method will create statistics based on the numbers in the array
public static void createData()
{
//Sum
double sum = myArray.Sum();
Console.WriteLine("The total sum of the array is: " + sum);
//Average
double average = sum / myArray.Length;
Console.WriteLine("The average number of the array is: " + average);
//Maximum
double maximum = myArray.Max();
Console.WriteLine("The maximum value in the array is: " + maximum);
//Minimum
double minimum = myArray.Min();
Console.WriteLine("The minimum value in the array is: " + minimum);
//Mean
double mean = sum / myArray.Length;
Console.WriteLine("The mean average of the array is: " + mean);
}
//This method will exit the program
public static void exitProgram()
{
Environment.Exit(0);
}
}
}
does my findData() method look ok?
Your findData() method does acutally nothing.
Here is one approach
public static void findData()
{
Console.WriteLine("Find a number");
string myChoice = Console.ReadLine();
double number = -1;
if(!Double.TryParse(myChoice, out number))
{
Console.WriteLine("Invalid number");
}
else if (Array.IndexOf<double>(myArray, number) == -1)
{
Console.WriteLine("Number does not exist");
}
else
{
Console.WriteLine("Number does exist");
}
}
This should solve your add problem
public static void addData()
{
for (int i = 0; i < myArray.Length; i++)
{
bool success = false;
while (!success)
{
Console.WriteLine("Enter a number you would like to add");
string input = Console.ReadLine();
double number;
if (Double.TryParse(input, out number))
{
success = true;
myArray[i] = number;
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number")
}
}
}
}
Your addData method doesn't make much sense: you first insert a double value into array and then you check if that value is a double (and it certainly is, because the array is of type double and can contain values only of that type).
Also, the Convert.ToDouble may throw exception if the user input is not valid. But I see you get the point of using Double.TryParse method, which returns true if the string (first parameter) is a valid number. So your addData method should look something like this:
//This method will add numbers to the array
public static void addData()
{
double number;
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Enter a number you would like to add");
// read user input
string input = Console.ReadLine();
// condition is true if user input is a number
if (double.TryParse(input, out number))
myArray[i] = number;
else
Console.WriteLine("Invalid input. Please enter a valid number");
}
}
To find a number in your array you can use LINQ Contains extension method which does exacly that: it returns true if array contains element, otherwise false:
//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
double number;
Console.WriteLine("Find a number");
string input = Console.ReadLine();
// we use the same logic here as in the addData method to make sure the user input is a number
if (!double.TryParse(input, out number))
{
bool found = myArray.Contains(number);
if (found)
Console.WriteLine("Array has number {0}", number);
else
Console.WriteLine("Array doesn't have number {0}", number);
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number");
}
}

Categories