Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only assignment, call, increment

Tags:

c#

double number;
string message;

Console.WriteLine("Welcome and enter a number.");
number = double.Parse(Console.ReadLine());

if (number < 0)
    message = "Your number is Negative";
else
    (number > = 0)
    message = "Your number is Positive"; 

Console.WriteLine(message);
Console.ReadLine();

I'm making this program for a class in school, and I'm getting an error with the line: (number > = 0) I have no idea what I'm doing wrong. The error message says

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.

like image 226
Kari Avatar asked Feb 27 '26 04:02

Kari


2 Answers

else statements cannot have a conditional applied to them, they simply run if every if and else if in the same "block" does not run.

So your conditional expression doesn't make sense, and is read as a statement to the compiler (which it is not).

Simply make your else an else if to fix the error:

   else if(number >= 0)
        message = "Your number is Positive"; 

Or just remove the conditional, since a number not less than 0 must be greater than or equal to 0.

   else
        message = "Your number is Positive"; 
like image 128
BradleyDotNET Avatar answered Feb 28 '26 21:02

BradleyDotNET


You can't have a condition in else part with if. In fact you don't need that at all. Since that is the cause of error so change else (number > = 0) to just else. Also Use {} to define scopes for if and else part.

So your code should look like:

double number;
string message = null;

Console.WriteLine("Welcome and enter a number.");
number = double.Parse(Console.ReadLine());

if (number < 0)
{
    message = "Your number is Negative";
}
else
{
    message = "Your number is Positive";
}

Console.WriteLine(message);
Console.ReadLine();

{} would be useful/required if you want multiple statements to be part of if or else block. Just having that for single statement is optional but probably a good practice, IMO.

You should also look for double.TryParse or TryParse group of methods for parsing, since they will not raise an exception in case of failed parsing, like:

if (!double.TryParse(Console.ReadLine(), out number))
{
    Console.WriteLine("Invalid number");
    return;// early exit or use a loop to ask again
}
like image 31
Habib Avatar answered Feb 28 '26 20:02

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!