Using int in try outside of context - c#

Console.Write("Write a number: ");
try
{
int Number = Convert.ToInt32(Console.ReadLine());
}
catch ( OverflowException )
{
Console.WriteLine("Number to big");
}
TellLastNumber(Number);
It says the 'Number' does not exist in the current context.
How can I make the int 'Number' used everywhere in the main()?

How can I make the int 'Number' used everywhere in the main()?
Just move declaration of variable Number to the scope of main() and it will be available from that point to the end of the function.
Console.Write("Write a number: ");
int Number = 0;
try
{
Number = Convert.ToInt32(Console.ReadLine());
}
catch ( OverflowException )
{
Console.WriteLine("Number to big");
}
TellLastNumber(Number);

To get rid of the error you have to define the Number outside of the try block and assign it some default value.
int Number = 0;
try
{
int Number = Convert.ToInt32(Console.ReadLine());
}
catch ( OverflowException )
{
Console.WriteLine("Number to big");
}
TellLastNumber(Number);
But more importantly use int.TryParse, that will not raise an exception if the number passed to it is not an int.
int Number;
if (!int.TryParse(Console.ReadLine(), out Number))
{
Console.WriteLine("Invalid number");
}
TellLastNumber(Number);
You are getting the error, because compiler can't see Number outside the scope of try.

Related

C# - How to handle errors in this code using try-catch block?

I have this code:
else if (number == 5)
{
Console.Write("Student's index: ");
int index1 = int.Parse(Console.ReadLine());
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
I need to handle errors using try-catch when the user doesn't enter any character or enters a non-integer character. How can that be done?
Use TryParse to check if the input is an integer or not. Then if it's an integer, do whatever you want with the index.
else if (number == 5)
{
Console.Write("Student's index: ");
var success = int.TryParse(Console.ReadLine(), out int index1);
if (success)
{
//next logic here if the input is an integer
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
else
{
//do something when the input is not an integer
}
}
You need to move your int.Parse line inside the try {} block. Only then will it be in the safety net of structured exception handling. You can then add a second catch {} block against a FormatException see Int32.Parse docs for exceptions thrown.
else if (number == 5)
{
Console.Write("Student's index: ");
try
{
int index1 = int.Parse(Console.ReadLine());
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
catch (FormatException)
{
Console.WriteLine("Error: Index must be a number.");
}
}

Trying to get program to handle error exception when non-numbers are input

This code currently handles inputs of numbers just fine whether greater or less or within the accepted range, however, the program crashes when anything that isn't a number is entered with an unhandled exception error.System.FormatException: 'Input string was not in a correct format.' That's the error if that helps at all.
using System;
class Program
{
static void PrintHello(int NumberOfTimes)
{
if (NumberOfTimes > 1 && NumberOfTimes < 11)
{
for (int Counter = 0; Counter < NumberOfTimes; Counter++)
{
Console.WriteLine("Hello.");
}
}
else { Console.WriteLine("Error, please enter a number between 1 and 10"); }
}
static void Main(string[] args)
{
int myNumber = 1;
while (myNumber != 0)
{
Console.WriteLine("Enter a number between 1 and 10, or 0 to stop");
myNumber = Convert.ToInt16(Console.ReadLine());
PrintHello(myNumber);
}
}
}
Just replace your Convert.ToInt16(...) with the following:
var input = Console.ReadLine();
if (int.TryParse(input, out myNumber))
{
PrintHello(myNumber);
}
The int.TryParse-method will return true, if the given input can be parsed as an integer, otherwise false. If it could parse the input, the value will be stored in the second parameter (which is flagged as out.
Edit:
As a rule of thumb: Never parse user-input directly (especially when you are handling with strings as input). Check if the input is valid.
You can use try and catch when parsing the input string as shown here:
try
{
int NumberOfTimes = int.Parse(Console.ReadLine());
}
catch(System.FormatException)
{
Console.WriteLine("Incorrect format of the user's input");
}

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

Declaring variable within 'while loop' but can't change value during loop

I'm trying to make this loop work so it will keep asking for a number until the user enters 999. However with this version of code, it won't build saying I can't declare num within the loop becuase I'm giving it different meaning in this scope.
The try and catch are used because of my assignment rules for this piece of code.
int num;
while (num != 999)
{
Console.WriteLine("Enter a number between 0 and 99");
string input = Console.ReadLine();
try
{
int num = Convert.ToInt32(input);
Console.WriteLine("This is element number " + num + " : " + randNums[num]);
}
catch
{
Console.WriteLine("Data inputted is not between 0 and 99");
}
}
Console.WriteLine("You chose the secret value, well done!");
The problem is that you're declaring the variable twice with int num. You don't need to redeclare the variable within the loop, just assign it:
int num = 0; // initialized num to 0 here
while (num != 999)
{
Console.WriteLine("Enter a number between 0 and 99");
string input = Console.ReadLine();
try
{
num = Convert.ToInt32(input); // Changed int num to num here
Console.WriteLine("This is element number " + num + " : " + randNums[num]);
}
catch
{
Console.WriteLine("Data inputted is not between 0 and 99");
}
}
Console.WriteLine("You chose the secret value, well done!");
You have int num defined twice in the same scope. Change the name of one of them. The one inside the loop is invalid since you already have one defined.
Alternately you can remove int from the inner one if you want to re-assign the same variable. This way it will overwrite it each time with a new value.
Also when you initialize it the first time, be sure to assign it a value.
Example:
int num = 0;
In addition to other answers, you can do this, for example:
if (someCondition)
{
int num = 23;
}
else
{
int num = 12;
}
But you can't do this:
int num = 12;
if(someCondition)
{
int num = 23;
}
Because all variables has it's own scope, and if you define a variable in outer scope, you can't define a new variable with the same name in the inner-scope.So if you just want to update the value of your variable, you don't need to declare it again, just use a simple assignment.See Compiler Error CS0136 documentation for more details.
You're trying to declare 2 different variables of the same name. Instead of declaring the second one, just use the one you already declared (take off inton the second usage).
...
try
{
num = Convert.ToInt32(input); // <-- Using existing declaration here
Console.WriteLine("This is element number " + num + " : " + randNums[num]);
}
...
You have two int variables with the same name. You need to change the other one since you have an int variable for the input that will accept the number assigned by the user, and another int variable responsible for detecting whether the number inputted is 999 or not.

Comparing an int value to an array, then display if value matches or does not match

I am brand new to programming and was interested in C#. I am studying arrays and have to compare my variable (checkNum) to my array(myNums[10]). I read posts here and several other sites and saw how to compare but getting stuck on how to properly display the comparison as shown in my attempt with the if/else statement below:(I will continue to research, but would appreciate and nudges in the right direction. Not necessarily the answer as I am wanting to learn) :)
Here is my code:
int[] myNums = new int[10];
int checkNum;
Console.WriteLine("Enter 10 numbers:");
for (int i = 0; i < 10; i++)
{
Console.Write("Number {0}: ", i + 1);
myNums[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("You entered:");
foreach (int x in myNums)
{
Console.Write("{0} ", x);
}
Console.ReadLine();
Console.WriteLine("Enter another number:");
checkNum = int.Parse(Console.ReadLine());
bool exists = myNums.Contains(checkNum);
if (checkNum == myNums[10])
{
Console.WriteLine("Your number {0} is in the Array.", checkNum);
}
else
{
Console.WriteLine(
"Your number {0} does not match any number in the Array.",
checkNum);
}
Console.ReadLine();
bool exists = myNums.Contains( checkNum );
if( checkNum == myNums[10] )
{
Console.WriteLine( "Your number {0} is in the Array.", checkNum );
}
else
{
Console.WriteLine( "Your number {0} does not match any number in the Array.", checkNum );
}
Should be
bool exists = myNums.Contains( checkNum );
// or simply if(myNums.Contains(checkNum)) as you don't use the variable again
if( exists )
{
Console.WriteLine( "Your number {0} is in the Array.", checkNum );
}
else
{
Console.WriteLine( "Your number {0} does not match any number in the Array.", checkNum );
}
You perform the check correctly, but you don't use the result (exists) and simply (attempt to) compare the new number to the last element in the array. Of course, at this point your program just crashes because you have overrun the bounds of your array.
Arrays are 0 indexed, i.e., nums[10] contains indices 0-9.
You need to iterate through the array to see if the value is in it:
bool exists = false;
for (int i=0; i<myNums.Length; i++)
{
if (checkNum == myNums[i])
{
exists = true;
break;
}
}
if (exists)
{
Console.WriteLine("Your number {0} is in the Array.", checkNum);
}
else
{
Console.WriteLine(
"Your number {0} does not match any number in the Array.",
checkNum);
}
Why do you have the last if statement checking for: checkNum == myNums[10]? It should use the exists variable.

Categories