Reputation: 21
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.
Upvotes: 2
Views: 864
Reputation: 19
Students will learn == sign too
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 if(number == 0)
{
message = "Your number is Zero";
}
else
{
message = "Your number is Positive";
}
Console.WriteLine(message);
Console.ReadLine();
mark answer
Upvotes: 0
Reputation: 223217
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
}
Upvotes: 2
Reputation: 61339
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";
Upvotes: 9