Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm a student sitting a course in computing for the very first time and I've been trying to 'crack' this one for ages (I'm very new to this... sorry!). I can't seem to build a simple if/else statement in which if the conditions are met, it writes a positive response, and if not, a negative response. But I'm getting the errors:
Invalid expression term 'else'
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Sorry if this makes no sense, I'm very confused! :(
static void Main(string[] args)
{
Console.WriteLine("Do you like bananas?");
Console.ReadLine();
if (Console.ReadLine() == "Yes") ;
{
Console.WriteLine("Thanks for your time!");
}
else;
{
Console.WriteLine("Oh okay.");
}
}
}
}
you need to remove the semicolon that you have after the else.
generally its
if (condition)
{
//code
}
else
{
//code
}
and if you have more than one condition to meet you can have
if (condition)
{
//code
}
else if (condition 2)
{
//code
}
else
{
//code
}
the last else is used if none of the conditions are met above, its like a default behavior
Further, you don't need braces for only one line of code
if (condition) DoInterestingStuff();
else DoNotDoInterestingStuff();
A few example conditions(with unnessesary if-statements for clarification):
if (bananas == true)
if (bananas) // same as above
if (bananas != false) // not equal to false, thus true
if (totalBananas >= 10)
No semi-colons:
if (Console.ReadLine() == "Yes")
{
Console.WriteLine("Thanks for your time!");
}
else
{
Console.WriteLine("Oh okay.");
}
Conditional Logic though is simple, basic, it is incredibly important to learn correctly. Your forgetting quite a bit of items:
Incorrect placement of ;.
You did:
if(Console.ReadLine() == "yes");
else;
The ; at the end of that particular portion of the statement is invalid. If your using Visual Studio or another IDE don't fight the tools, they try to help you with issues such as this. For instance a squiggly line should appear under the ; in that statement.
Your if else should be formatted in this manner:
if(value == "Yes")
{
Console.WriteLine("Thank you...");
}
else if (value == "No")
{
Console.WriteLine("No!");
}
else
{
Console.WriteLine("Ah...");
}
You'll want to familiarize yourself with the if else and switch statement early on. They're key piece in the foundation. You can find some more detail on the Microsoft Developer Network. Really good examples an explination of the entire process.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have been doing some C# practice problems for a while and I want to start playing with ternary operations to make my code cleaner.
Here is my code:
public static string Bomb(string txt)
{
txt.ToLower().Contains("bomb") == true ? "Duck!!!" : "There is no bomb, relax.";
}
So basically if Bomb("xxxxxx") contains the string "bomb" it will return "Duck!!!" if not it will return "There is no bomb, relax."
But for some reason, this doesn't work and I can't figure out why.
You just need to add return
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") == true ? "Duck!!!" : "There is no bomb, relax.";
}
Your ternary operator looks OK, but you're missing a return statement from the function. Also note that Contains returns a boolean, so the == true is redundant:
So I have been doing some c# practice problems for a while and I want to start playing with ternary operations to make my code cleaner.
Here is my code:
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}
you missed the return part in the function
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
i just started out with C# and im confused by a Compile Error.
This is the Code:
namespace Control_Flow_1
{
class Program
{
static void Main(string[] args)
{
string UserInput;
int Number;
Console.WriteLine("Bitte geben sie eine Nummer von 1-10 ein");
UserInput = Console.ReadLine();
Number = Convert.ToInt32(UserInput);
if (Number >= 1 && Number <= 10);
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Invalid");
}
}
}
}
The } after the Console.WriteLine; seems to do the Compile Error for some Reason, how to fix it ?
Compile Error:
if (Number >= 1 && Number <= 10); get rid of the semi colon.
With the semi colon after the if you have
if ()
a block of code
else (with no corresponding if)
a block of code
The semi colon ends the if statement and so you have a "floating" else with no previous if
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am wondering can someone please tell me where I am going wrong with this FizzBuzz.
I get an error "not all code returns a value and struggling to find out exactly how to fix it.
My code is below:
for (int i = 0; i < input; i++)
{
if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else
{
Console.WriteLine(i);
}
}
And the test case is this:
[Test]
public void Test1()
{
var solution = new Solution();
Assert.AreEqual(solution.PrintFizzBuzz(15), "FizzBuzz");
}
First of like other people have said, not all the code is present so it's difficult for us to help. But I'll try anyway.
When testing with Assert.AreEqual the function PrintFizzBuzz should return something, in this case the string "FizzBuzz". But if you are using the Console.WriteLine method it will return nothing. The Console.Writeline method will print the string to the console, but the console is not actually the 'program', it's just for visualising some things like logging or debugging.
So to fix your issue you should use return instead of Console.Writeline and let your method PrintFizzBuzz return a string instead of voiding and printing it to the console. It's probably also better to rename your method in this case, because it doesn't print FizzBuzz anymore.
Your code has also another issue and that's when you input 15 it will print out "Fizz", because the check you do is modulo 3 and 15 % 3 = 0. You should order your check the otherway around, from specific to less specific.
An example for returning a string would be:
string SomeMethod()
{
return "Some String"
}
not all code returns a value
Means your method declared having a return type and not void but you are not returning anything from your method. One example case:
int Add(int a, int b)
{
int c = a + b;
// no return specified would through the same error
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've been coming across not equal != or !condition in conditional statements ever since I started programming. Maybe it's because my brain is pre-conditioned in the English language to overthink multiple negation. But I have been wondering, is there a common development community accepted practice when it comes to evaluating for true in conditional statements? Or rather, the way I see it sometimes: evaluating for not false.
Maybe there are exceptions where != cannot be completely unavoidable?
For Example:
This might be a very simple and trivial, but is this preferred
string myStringVar = "dogs";
if (myStringVar != "dogs") //In my mind, "False this is not true"
{
//code
}
else if (myStringVar != cats) //In my mind, "True this is false"
{
//code
}
Or is this preferable
if (myStringVar == "dogs")
{
//"True"
}
else if (myStringVar == "cats")
{
//"False"
}
Then there's
bool MyBoolMethod()
{
return false;
}
if (!MyBoolMethod()) // True this method does not return true
{
//code
}
This is a very trivial and simplified example, I just want to know how to write readable, maintainable code. Does anyone else have a somewhat difficult time reading conditionals like this or is it just me?
"None of the above."
Since you're using strings, the assumption is that myStringVar can be anything. If I say:
string myStringVar = "Aardvark";
Then your first example, it will run the myStringVar != "dogs" section of code; In the second example, neither will be executed. So they're not equivalent pieces of code.
The only way they would be equivalent is if you were using Enums (in which case I would suggest using a case statement).
In your third example, it would depend on what MyBoolMethod() was named, and how easy it was to understand by a future coder. To use an example,
bool isDog()
{
return false;
}
is is easy to understand. The question then becomes is
if(!isDog()) ...
more clear than
if(isNotDog()) ...
I would argue that the first is more clear than the second. There are other situations, however, where that is not the case.
Equality and inequality are just something one needs to get comfortable with and choose in context. If the logical problem requires looking to test against equality use equality if it is looking to disqualify use inequality.
The readability and maintainability can be reinforced through good design as you started to allude to with your mybool method.
Exmaple
public class Animal
{
public static Enum AnimalType
{
Dog,
Cat
}
private _animalType;
public Animal(Enum AnimalType type)
{
AnimalType = _animalType;
}
public bool isOfType(Enum AnimalType type)
{
return _animalType == type ? true : false;
}
}
public someothermethod()
{
//doing inclusion
If(MyAnmialObject.isOfType(Animal.AnimalType.Dog))
{
//if type matches
}
//Doing exclusion
If(!MyAnmialObject.isOfType(Animal.AnimalType.Dog))
{
//if type does not match
}
}
You still have to get used to inequality but you know it is checking for isOfType and the named type.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Question: My else-statement is unreachable, what am i doing wrong?
very VERY new at programming and i'm trying to compare the type so for example people can't enter strings when i'm asking for integers.
My code is probably pretty bad, if i could get a header what to do and why the if-argument skips the else-part i'd be really happy!
Thanks!
class Program
{
static void Main(string[] args)
{
int integer = 0;
start:
Console.WriteLine("How old are you?: ");
int svar = int.Parse(Console.ReadLine());
Utility.CompareTypes(svar, integer);
if (true)
{
Console.WriteLine("Thanks");
}
else
{
Console.WriteLine("You have to enter a number!");
goto start;
}
}
}
class Utility
{
public static bool CompareTypes<T01, T02>(T01 type01, T02 type02)
{
return typeof(T01).Equals (typeof(T02));
}
}
:c
It's not really a question of code, but of logic...
if (true) // <--- this will ALWAYS be true
{
Console.WriteLine("Thanks");
}
else // <--- therefore this will NEVER happen
{
Console.WriteLine("You have to enter a number!");
goto start;
}
Since your else block can never possibly execute under any logical circumstance, the entire block of code can be simplified to:
Console.WriteLine("Thanks");
In order for the else block to execute, the condition checked in the if statement needs to be false. You're currently not checking any actual condition, just a hard-coded true value.
Perhaps you meant to use the result of the previous line of code? Something like this:
var typesAreSame = Utility.CompareTypes(svar, integer);
if (typesAreSame)
{
//...