its_siobhanx
its_siobhanx

Reputation: 21

Operator / cannot be applied to operands of string and double C#

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
        }
    }
}

Upvotes: 0

Views: 132

Answers (2)

RemarkLima
RemarkLima

Reputation: 12047

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504172

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.)

Upvotes: 6

Related Questions