Frederick
Frederick

Reputation: 13

Why does this code not work when I try to convert it

This is only a small piece of the code I'm trying to make work. The original code I wrote works but I want to make sure when the user inputs a number it is in fact a number.

Console.WriteLine("Give the number of A");
A =Convert.ToDouble( Console.ReadLine());

if (char.IsNumber(Convert.ToDouble(A)) == correct)
{
    Console.WriteLine(Convert.ToDouble( A * A));  
   
}
else
{
    Console.WriteLine("Incorrecrt input");
}
           

The Console.WriteLine(Convert.ToDouble(A*A)); I only wrote to see if that will work and it doesn't. After the user inputs only a number I must use it in another equation for a final answer. The user must input 3 numbers.

Upvotes: 0

Views: 156

Answers (2)

Coskun Ozogul
Coskun Ozogul

Reputation: 2487

For me, you should check is the input is a number that you can convert to double before converting it.

       Console.WriteLine("Give the number of A");
       
        var a = Console.ReadLine();
        double number;
        if (double.TryParse(a, out number))//double.TryParse takes a parameter and tries to convert it to double. If the convertion is successfull, sets the out parameter as result and returns true. If not, returns false. And you can use with other types like int.Tryparse(param, out outParam);
        {
            A = number;
        }
        else
        {
          //Not a number, show a message etc...
        {

Upvotes: 2

WSC
WSC

Reputation: 1002

If you break this down:

A =Convert.ToDouble( Console.ReadLine());
if (char.IsNumber(Convert.ToDouble(A)) == correct)
{

}

What you're basically doing is:

Double A = Convert.ToDouble(Console.ReadLine());
Double dbl = Convert.ToDouble(A);
Boolean bl = char.IsNumber(dbl);

if (bl== correct)
{

}

So there's multiple things wrong here.

Firstly, you're trying to convert the user input without any sort of guarantee of success, so if someone typed "A" instead of a number it will throw an exception.

You should use TryParse and then if it's a valid conversion proceed.

Secondly, you're checking if a Double is a char that can be converted to a number. Obviously not because it's already a Double.

Thirdly, you're checking if a Boolean is equal to some variable called correct (which you haven't provided the definition of) so it's not clear if this is a valid comparsion.

EDIT:

This is what I would do:

bool validInput = false;
do
{
    Console.WriteLine("Give the number of A");
    string userInput = Console.ReadLine();

    if (double.TryParse(userInput, out double result))
    {
        validInput = true;
        Console.WriteLine(result * result);
        Console.ReadLine();
    }
    else
    {
        Console.WriteLine("Invalid input. Please type a number.");
    }
} while (!validInput);

Upvotes: 2

Related Questions