Hi there

Im trying to program a simple project for school but am having troubles. I need to ask a person to enter a number which displays on screen, then multiply that same number buy itself. I can get the number entry part but keep getting errors from that point on. Can anyone steer me in the right direction as I'm going around in circles lol.

Much thanks for your help
Emma


Here is my code so far.

string number;
int timesNumber;

Console.Write("Please enter a number");
number = Console.ReadLine();

timesNumber = number *

timesNumber = number * number;

number is a string, returned from ReadLine.
You first have to convert it to an integer value, before you can do calculations with your input.
Use int.TryParse or the Convert.ToInt32 method to do that.

commented: Thanks for noticing. +2
commented: Stop being right all the time!! :P +1

finito is right, you need to actually multiply the number BY something.
Is it possible you got confused by the alternative syntax of number*=number ? If you are operating on the same variable that will store the result you can use this as a shorthand.
For example:

int number;
number = number + 1;
//is the same as
number += 1;

//or
number = number - number
//is the same as
number -= number

You may also want to explicitly convert the string to an integer. Your application will throw an exception if your user enters "a" as the number, or "1.2".
I generally recommend the use of int.TryParse(string, out int) as it will return a boolean value to tell you if it has succeeded. You can then either proceed, or inform the user of invalid input based on the return value.

Thanks ddanbe, I didn't notice that.

or you could do this.

int number;
int timesNumber;

Console.Write("Please enter a number");
number = int.Parse(Console.ReadLine());

timesNumber = number * number;

ddanbe is right of course...you NEED to convert the number. Just checked and the compiler wont implicitly convert it for you

Just to bring this together, between us we have shown the three main methods to convert a string to an int. Of the three, i would always suggest int.TryParse when dealing with user input. If the user enters a value that cannot be converted, Convert.ToInt32 and int.Parse will both throw a FormatException.

True TryParse is Ideal in this situation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.