0

I am familiar with programming, but not with C#. I am currently learning it right now, but I am kinda struggling with some errors.

(I couldn't find this question in an other post)

Code:

public static void Main(string[] args)
{
     myFunction();
}

public static void myFunction() {
{
    Console.WriteLine("Enter a number: ");
    int resultOne = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter another number: ");
    int resultTwo = Convert.ToInt32(Console.ReadLine());

    var max = (resultOne > resultTwo) ? resultOne : resultTwo;
    Console.WriteLine("Max number is: {0}", max);
}

Errors:

Enter a number: 
6
Enter another number: 

Unhandled Exception:
System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber (System.String str,                                
System.Globalization.NumberStyles options, System.Number+NumberBuffer& 
number, System.Globalization.NumberFormatInfo info, System.Boolean 
parseDecimal) [0x00057] in <9790d962aaad40deb63d33029ba0d2f6>:0 

Probably a rookie mistake, but I don't see what I am doing wrong. The errors appears after passing the second input lines.

Also, the last 'max' in the Console.WriteLine says: 'Boxing allocation: Conversion from value type 'int' to reference type 'object'.

I also tried Int32.Parse instead of Convert.ToInt32 but nothing changes. (Not sure what the difference, but I tried).

Can you help me in de right direction?

edit 1

I changed my code to:

Console.WriteLine("Enter a number: ");
var input1 = Console.ReadLine();
int resultOne = Convert.ToInt32(input1);

Console.WriteLine("Enter another number: ");
var input2 = Console.ReadLine();
int resultTwo = Convert.ToInt32(input2);

var max = (resultOne > resultTwo) ? resultOne : resultTwo;
Console.WriteLine("Max number is: {0}", max);

I get your point, but I don't get the change to enter a second value. I understand when I don't enter any value other than an integer, I could get errors. But it crashes right away

J. Doe
  • 35
  • 4
  • You'll find *thousands* of duplicate posts and the error clearly explains what's wrong - you tried to parse a string that *isn't* a number. What did you enter? Where did the exception occur? What was the string? Hint: an empty string isn't a number – Panagiotis Kanavos Nov 08 '17 at 10:55
  • I couldn't even get to the point where I can enter the second number - that's my point. It crashes on the line; int resultTwo = Convert.ToInt32(Console.ReadLine()); I don't understand why. – J. Doe Nov 08 '17 at 10:57
  • Store the string to a variable and check it. `Convert.ToInt32(Console.ReadLine())` means that you can't check the string at all. – Panagiotis Kanavos Nov 08 '17 at 10:59
  • Besides, your output shows that you *did* reach the line and *did* read input from the console. That input was an empty string – Panagiotis Kanavos Nov 08 '17 at 11:00

0 Answers0