The code below is a snippet from a working code that is for a castle maze game in c#.
The if else structure only prints correctly the dun.roomend == true). The tow.roomEnd now displays when the tre.isExit should be displayed. The tre.isExit doesn't display at all.
I have declared the current variables as:
public bool isExit;
public bool deadEnd;
public bool roomEnd;
tre.isExit = true;
dun.deadEnd = true;
tow.roomEnd = true;
if (dun.roomEnd == true)
{
Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
return;
}
if (tow.roomEnd == true)
{
Console.WriteLine("You been caught by the Kings guard and have been placed in the tower for life.Try again");
return;
}
else if (tre.isExit == true)
{
Console.WriteLine("You have found the treaure... now run!!");
return;
}
else
{
Console.WriteLine("Too scared.....");
}
That's because you immediately return when one of your conditions is true.
// Don't explicitly compare to true - just write if (dun.roomEnd)
if (dun.roomEnd == true)
{
Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
// You end the method here, so none of the rest of the code after this will execute
return;
}
Also, the fact that you do
else if (tre.isExit == true)
means that this won't execute if
tow.roomEnd == true
is also true. "Else if" means "if the current condition is true and the previous condition is false", so
if (A) {
// do work
}
else if (B) {
// Do work
}
is semantically equivalent to
if (A) {
// Do work
}
if (!A && B) {
// Do work
}
Finally, I mentioned this in passing, but I'd like to reiterate that it's not necessary to explicitly compare to true or false, so
if (tow.roomEnd == true)
should just be
if (tow.roomEnd)
Also, I don't think it makes sense for all of those conditions to be true at once. Can something actually be a room end, a dead end, and an exit at the same time? At a minimum, it seems like a particular location can't be both an exit and a dead end. If the data says that several of those things are true at once, it needs to be corrected in order for the program to function properly.
In every if statement you have keyword return;. The return statement terminates execution of the method and because of that only first Console.WriteLine is shown.
Read carefully: return (C# Reference)
Reading through what you've done, if I'm understanding this correctly what you're after is as follows.
public bool isExit;
public bool deadEnd;
public bool roomEnd;
tre.isExit = true;
dun.deadEnd = true;
tow.roomEnd = true;
if (dun.roomEnd == true)
{
Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
}
else if (tow.roomEnd)
{
Console.WriteLine("You been caught by the Kings guard and have been placed in the tower for life.Try again");
}
else if (tre.isExit)
{
Console.WriteLine("You have found the treaure... now run!!");
}
else
{
Console.WriteLine("Too scared.....");
}
return
This will evaluate each condition individually, and then return once complete.
What this code is effectively saying is "if condition 1 is true, display the text and exit the if block, then return. Otherwise if condition 2 is true do the same, condition 3 / 4 do the same thing also.
I think this is what you're after at least. It could be refactored to make it a little simpler but don't have the time to go over that at the moment.
Assuming it is showing the Dungeons of the Dead and the Kings Guard message, you need to add an "else" to the if for tow.roomEnd.
Related
I'm just starting out so I'm in the middle of writing my first console application from scratch. I have this line of code, when I hit d it correctly takes me to the next step and sets disadvantage to true, however if I hit a it executes the else statement for some reason. Any ideas what the cause is?
Console.WriteLine("Press the A key for advantage, or the D key for disadvantage");
var rollType = Console.ReadKey();
Console.WriteLine(System.Environment.NewLine);
if (rollType.Key == ConsoleKey.A)
{
advantage = true;
}
if (rollType.Key == ConsoleKey.D)
{
disadvantage = true;
}
else
{
Console.WriteLine("Invalid Input");
StartApp();
}
Just add make this small change! (Adding else in your second conditional)
if (rollType.Key == ConsoleKey.A)
{
advantage = true;
}
else if (rollType.Key == ConsoleKey.D)
{
disadvantage = true;
}
else
{
Console.WriteLine("Invalid Input");
StartApp();
}
What was happening before is your Console would read an A key and enter the first conditional. Since the second and third conditional was separate from the first, the second would also be checked and if not true (which in this case it would not be true) it would no matter what enter the else statement. Hope this helps.
Seems like the program is being executed exactly as you’ve written it to.
if (rollType.Key == ConsoleKey.A)
{
advantage = true;
} // First conditional check ends here
// This is another conditional block
if (rollType.Key == ConsoleKey.D)
{
disadvantage = true;
}
else // You pressed A, so this block is executed
{
Console.WriteLine("Invalid Input");
StartApp();
}
If you hit A, it will excude A and else part of D. After all, A equals A but A does not equal D.
What you want is propably a switch/case statement.
switch(rollType){
case ConsoleKey.A:
advantage = true;
break;
case ConsoleKey.D:
disadvantage = true;
break;
default:
Console.WriteLine("Invalid Input");
break;
}
switch/case statement and do/while loop - these two are the fundament of console programm flow.
How do I do this? I have an if-else statement like this (not exact code but a symbolic idea):
if(formNull)
{
MessageBox.Show("empty")
}
else if(FormNotNull)
{
// I have validation if/elses here for input fields like
if(regex textbx1)
{
error
}
else
{
normal
}
if(regex textbx2)
{
error
}
else
{
normal
}
//Some more like this
} <<<<<<<<<<<< It stops here and never goes in the next 'else' statement even if the form is OK.
else
{
DBConn.myMethod(a, b, c, etc.)
if true
{
success!;
}
else
{
failed!;
}
}
I tried some nesting combinations, but nothing worked.
Seems like there's nothing left, as you already handled all cases in the if and else if.
if(formNull)
{
// goes here when `formNull` is true
}
else if(FormNotNull)
{
// goes here when `FormNotNull` is true and `formNull` is false
}
else
{
// goes here in any other case (but I guess there is no other case left)
}
That just means your two conditions (in the if and else if statements) are returning true. If either ever returns true, you will never go into your else block (both MUST be false).
Thank you all for suggestions. I simply used the separate textChanged events with Regex for errors and used simple if-statement like this
if (FormNull)
{
Message.Show("error");
}
else
{
DBConn.myMthod(a,b,c)
if(true)
{
sucess;
}
else
{
failed;
}
}
Just wanted to know the other option for what I was trying to do.
I'm trying to use an if statement with a bool that will make it that if a code runs once it will not run again. Here is the code I am using.
int random = Program._random.Next(0, 133);
if (random < 33) {
bool done = false;
if(done)
{
continue; // Error is shown for this statement
}
Console.WriteLine("Not done!");
done = true;
}
The error that Visual Studio is displaying is: "No enclosing loop out of which to break or continue".
Depending on the class/method requirements, you could possibly reverse your logic:
if (!done)
{
Console.WriteLine("Not done!");
done = true;
}
You can't use a continue only inside a loop. So you must live without this:
int random = Program._random.Next(0, 133);
if(random < 33)
{
bool done = false;
if(!done)
{
Console.WriteLine("Not done!");
done = true;
}
}
In this case, you should reverse the if with if (!done) { ... }
You can't use continue like that, it can only be used in a loop. The continue statement will go to the end of the loop and continue with the next iteration, without a loop there is no end of the loop to go to.
You can use else instead:
if (done) {
// anything to do?
} else {
Console.WriteLine("Not done!");
done = true;
}
If there is nothing to do if the variable is true, you can just reverse the expression instead:
if (!done) {
Console.WriteLine("Not done!");
done = true;
}
Note: You need to store the variable done outside the scope. Now you have a local variable that is always set to false, so the code will never be skipped.
The exception is telling you that continue is ineffective here. It simply has nothing to do, and doesn't know where to continue. It is meant to be used within the iteration of a loop.
I have a program that is completely functional, and I am now refactoring it. I am just in the process of learning c# so the original code was pretty terrible despite the fact that it ran just fine. One of the requirements of the program is that the user be able to return to the main menu at any point. I accomplished this as follows:
static bool bouncer = false
static void Exit(string input)
{
if (input == "\t")
{
bouncer = true
}
}
static string Prompt(string msg)
{
// takes input and passes it to Exit() then returns the input
}
static string FunctionA()
{
while(true)
{
if (bouncer == true)
{
break;
}
Prompt("whatever")
if (bouncer == true)
{
break;
}
Prompt("whatever")
if (bouncer == true)
{
break;
}
// return some stuff
}
}
static void Main()
{
bouncer = false
// writes the menu to console and handles UI
// FunctionA
{
The variable bouncer gets set to true if the user enters the "tab" character at any input point. The proliferation of break statement conditionals provides the structure that actually breaks out back to Main(). This is obviously not a very good solution and it makes the code hard to read.
Other attempts that I considered to accomplish the same task are:
Goto statement that jumps straight back to Main(). I scrapped this because goto has a very limited scope in c# and I don't think there is any good way to make it workable in this situation.
Calling Main() directly from Exit(). This is probably a bad idea, and I can't do it anyway because apparently Main() is "protected" in some way.
Using an event to react to TAB or ESC being pressed. It's unclear to me how I could use an event to do this since I still wouldn't be able to break right out of the event. My understanding is that the break statement has to actually be contained in the loop that needs to be broken as opposed to being written into a different function that is called from within the loop.
Any suggestions are greatly appreciated. I'm hoping there's something to be done with event handling or that I've overlooked something more simple. Thanks!
As a matter of coding style, the way it is works, but is seen as ugly. Unfortunately, if you need to break out immediately between sections of work, there is not a lot of ways around that.
You can change your current format of using breaks to using "if( bContinue ) { /* do next section of work */ }" control style. It changes the code from break out of the while loop to this:
static string FunctionA()
{
bool bContinue = true;
while( true == bContinue )
{
// Do initital work.
//
// Initial work can set bContinue to false if any error condition
// occurs.
if( true == bContinue )
{
// Do more work.
int returnCheck = MakeACall(); // Presume MakeACall returns negative interger values for error, 0 or positive values for success or success with condition/extra information.
if( 0 < returnCheck )
{
bContinue = false;
}
}
if( true == bContinue )
{
Prompt("whatever")
// Do more work.
bContinue = MakeASecondCall(); // Presume that MakeASecondCall returns true for success, false for error/failure
}
if( true == bContinue )
{
Prompt("whatever")
// Do more work.
// If error encountered, set bContinue to false.
}
if( true == bContinue )
{
Prompt("whatever else")
// Do more work.
// If error encountered, set bContinue to false.
}
// Done with loop, so drop out.
bContinue = false;
// return some stuff
}
}
Looking at your pseudo code, it reads like you only do a single pass through your work loop. If so, you can switch to a Do-While(false) format, and use the break to just drop to the bottom. Or, if you are only doing a single pass through your FunctionA, just do away with the While or Do-While control structure, and just use the if(true==bContinue){ /* Do more work */ }. It is not the cleanest of code, but when you perform long periods of serial work, you end up with such structures if you are not going to use a while or do-while for controlling the flow.
The disadvantage to using the if(bContinue){} style is that when an error condition occurs during the early stages of the process, the code does not exit out as quickly from the function as a break out of the while() or do-while() structure if the error occurs near the top of the work, as there will be the series of if statements that the code will test and then skip over. But it is readable, and if you use a descriptive name for your control variable (ie, nContinue or bContinue or workLoopControl) it should be fairly obvious that it is the master control flag for the function's work flow to whoever works or reviews the code after you.
Instead of an infinite loop and break statements, try using a conditional flag instead.
static void FunctionA()
{
bool done = false;
string response = string.Empty;
while (!done)
{
response = Prompt("whatever");
if(response == '\t')
{
done = true;
}
}
}
As a side note, I'm not sure why you have 'string' as the return type of several methods (e.g., 'FunctionA') when you aren't using the return value. That's why the code I gave above has it as 'void'.
I have added one label in form that is not visible to user.Base on the text that label contain proceed further.
Here is my logic,but it fail.I wanted like this,if label contain "No match" or "Time out",should not proceed.
If((!label.Text.Contain("No match")) || label.Text.Contain("Time out"))
{
// proceed further code
}
else
{
// code
}
Here Label contain "No match",then it move to else part that is right.But when label contain "Time out",then it go inside the if loop.So I modified code like this
If((!label.Text.Contain("No match")) || (!label.Text.Contain("Time out")))
{
// proceed further code
}
else
{
// code
}
still not working.If label contain "Time out",still it go into if loop not else loop.Label contain only one text at a time either "No match" or "Time out" or any other text.
I suspect you want:
if(!(label.Text.Contains("No match") || label.Text.Contains("Time out")))
{
// proceed further code
}
else
{
// code
}
Note the bracketing. The inner part is
label.Text.Contains("No match") || label.Text.Contains("Time out")
and then that's inverted. I would probably pull that out into a separate variable:
bool timedOutOrNoMatch = label.Text.Contains("No match") ||
label.Text.Contains("Time out");
if (!timedOutOrNoMatch)
{
}
else
{
}
Alternatively, invert the sense of it:
if (label.Text.Contains("No match") || label.Text.Contains("Time out"))
{
// Do whatever was in your else block.
}
else
{
// Do whatever was in your first block.
}
If your response to the "bad" labels is something that lets you return or throw an exception, this can also reduce the amount of nesting:
if (label.Text.Contains("No match") || label.Text.Contains("Time out"))
{
output.Text = "Go away";
return;
}
// Now handle the success case
Try with following code:
if(!(label.Text.Contains("No match") || label.Text.Contains("Time out")))
{
// proceed further code
}
else
{
// code
}
If you want to get right with your modified code, use AND operator:
if(!label.Text.Contains("No match") && !label.Text.Contains("Time out"))
{
// proceed further code
}
else
{
// code
}
To write your code in more understood form , you should write it in a way that it is readable and more understandable. I prefer to write this statement like this
bool ProceedFurther()
{
//Don't proceed if No Match
if(!label.Text.Contains("No match")) return false;
//Don't proceed if Time out
if(!label.Text.Contains("Time out")) return false;
//Proceed otherwise
return true;
}
and call ProceedFurther method at desired location.
If you really want only that statement, following is the best (mostly people forget to change || to && after they change the condition to negative (using !).
if(!label.Text.Contains("No match") && !label.Text.Contains("Time out"))