0

Sorry I'm new to C# I believe I'm not converting my string to an int correctly. Any help

using System;

namespace planetage
{
    class Program
    {
        static void Main(string[] args)
        {
            const double jupiterYears = 11.86;
            string userAge;

            Console.WriteLine("Please enter your age"); //Ask for users age
            Convert.ToInt32(userAge = Console.ReadLine()); //take users age

            double mercuryAge = userAge / jupiterYears; //error message shows for this line
        }
    }
}
  • Does this answer your question? [Reading an integer from user input](https://stackoverflow.com/questions/24443827/reading-an-integer-from-user-input) and [int.TryParse with Console.ReadLine() in C#](https://stackoverflow.com/questions/27858574/int-tryparse-failing-with-console-readline-in-c-sharp/51806772) –  May 13 '21 at 11:24

2 Answers2

7

This line:

Convert.ToInt32(userAge = Console.ReadLine());
  • Reads a line of text
  • Stored it in the userAge string variable
  • Calls Convert.ToInt32 with that text
  • Ignores the result

Instead, you want:

int userAge = Convert.ToInt32(Console.ReadLine());

(And remove the earlier declaration of userAge. In general, it's a good idea to declare local variables at the point where their value is first known. Very occasionally that's not possible, e.g. if the value is assigned conditionally, but it's usually fine.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It looks like you have your assignment in the wrong part. Try:

using System;

namespace planetage
{
    class Program
    {
        static void Main(string[] args)
        {
            const double jupiterYears = 11.86;
            int userAge; // Change userAge to be an int

            Console.WriteLine("Please enter your age"); //Ask for users age
            userAge = Convert.ToInt32(Console.ReadLine()); //take users age

            double mercuryAge = userAge / jupiterYears; //error message shows for this line
        }
    }
}

So you assignment to the variable need to be the part we're assigning to.

RemarkLima
  • 11,639
  • 7
  • 37
  • 56