Hi I have only recently started using c# in my first year of university. I have done a little vb before but pretty much a noob.
I have to write a simple console application that counts how many coins are required to make up a particular number given by the user.
My question is how do I check that the input giving by the user is a valid integer before I convert the string (Num) to an Integer (i).
This is what I have:
while (Num = "")
Console.WriteLine("Please enter a value");
Num = Console.ReadLine();
If (Num !="")
i = Convert.ToInt32(Num);
Any help would be greatly appreciated also any constructive criticism is welcome.
1) Don't assume the input should be an integer. If you want to calculate the number of coins required, you should allow for dollars and cents. Use a double or decimal data type instead.
2) For validation, use the .TryParse(string input, out result) method. The method itself returns a bool, the out parameter (result) is what would contain the parsed value. You would use it like this:
string input = "10.75"; // change to user input!
double output = 0d;
bool validInput = double.TryParse(input, out output);
// other TryParse methods:
// could be more!
// ok to work with output value
// not ok to work with output value, consider prompting user for another value
The reason you want to use TryParse is that it gives you a boolean return value indicating success or failure. Other methods such as Convert.To[Type] or [Type].Parse will throw exceptions on invalid inputs. You can catch these and handle them the same way you would a false condition of TryParse, but it is inefficient to do so.
Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...
I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...