I have made a for loop with a nested if block. On exit of the loop I want the object to perform an action by calling a method. At the moment I am struggling to find how to do this. Could anyone make any suggestions?. Below is the code I have made.
public void goLoop()
{
for (int i = 1; i <= getAmountOfLoops(); i++ )
{
if (getPosition() => 25)
{
this.setPosition(4);
}
else
{
this.keepLooping();
this.setTotalAmountOfLoops(getTotalAmountOfLoops() + 2);
}
jump(); // Do I put the action to perform on exit of loop here?
}
Just call it after the loop:
for (... ) {
}
action();
BTW change getPosition() => 25 to getPosition() >= 25.
Note: It's always better to be aware of the logic of your program before you start coding, however if you start coding and suddenly encounter a trivial situation like this, just give it a try! and check if it produces the desired result or not.
Related
This is essentially what i'm doing
while(true) //cant check for zero, there is more to do here
{
int val = 0;
for(SomeObject i : arrayListOfSomeObjects)
{
if(canDoSomething)
{
val++
}
}
if(val == 0)
{
break;
}
else
{
//do stuff with that nonzero value
}
}
It is strange, because the loop wont yield. As in, stop if unsuccessful. I have a proceedure that will keep going until it finishes, if it does not do anything (or does not meet my conditions in that operation) it wont change the value. Meaning that check on "val" should break the loop. But it doesn't. It just going. I have even printed "val" to the console, yet it returns 0.
At the end of that operation, even if the value IS 0, it keeps going!
Your code is correct.. Try the following..
int val = 1;
while(val>0)
{
//Some operation that will change the value IF successful
}
first int val = 0 supposed to be outside the loop because this will cause the value of the variable val always zero
You might need to make sure you are targeting the 'right' loop by adding a label:
label: while(true) //cant check for zero, there is more to do here
{
// ...
if(val == 0)
{
break label;
}
// ...
}
This will ensure that you break out of the while loop in case the check is in another loop or a switch statement. Otherwise, I am sure that something is causing the problem that you didn't show in your example. Beware of unwanted side-effects.
retry: {
.........
if(xyz < 5) {
continue retry;
}
}
Problem : continue cannot be used outside of a loop
Why iteration of a block is prevented in java?
It's not supported because noone implemented it, presumably because they thought that, well, loops should be implemented with the loop constructs Java provides.
What you want to do can easily be implemented as a while loop if you invert the condition and use break instead:
while (true) {
.........
if(xyz >= 5) {
break;
}
}
Or why not write it as a regular loop without break or continue?
do {
.........
} while (xyz < 5);
Problem : continue cannot be used outside of a loop
continue is used within a loop i.e. for/while/do-while, if statements are conditional code blocks and not loops.
Learn more about code branching statements here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
The purpose of continue keyword is to skip rest of the code inside loop to start with the next pass of loop. So, by it's purpose, continue would not fit in the contexts outside the loops.
goto could be other option for you to reset (or restart) the code of execution. However the best way could be move such part into a method and use recursion along with return under specific conditions to achieve the purpose you are talking about.
As others have pointed out, labels in Java label loops, and are used to specify which loop to break or continue.
That said, if you really want to write "spaghetti code" you can misuse break and continue like for instance:
public class SillyGotoExmple {
public static void main(String args[]) {
int count, loops;
final int NUM_LOOPS=2;
final int MAX_COUNT=10;
loops=0;
bar: do {
count = 0;
foo: do {
System.out.println(count);
if(++count < MAX_COUNT) {
continue foo;
} else if(++loops < NUM_LOOPS) {
continue bar;
} else {
break bar;
}
} while (true);
} while(true);
}
}
For some more discussion on goto in Java, see e.g. Is there a goto statement in Java?
So I have a loop that is wrapped around a loop and an if statement. When running the program however, it gets out of the inner loop (as planned) and then it fails the if statement (also as planned), resorting to the else statement which is a simple print.
What I /wanted/ to happen was have it then (in the case the if fails), restart to the original inner loop--hence the outer loop. But instead, after it fails the if statement, it begins to loop "phrase2" over and over.
Here is the simplified code:
int x = 1;
int y = 1;
int i = 0;
while(i == 0)
{
while(<condition that is false>)
{
System.out.println("phrase1");
a = input.nextInt();
b = input.nextInt();
}
if(<condition that is false>)
{
i = 1;
}
else
{
System.out.println("phrase2");
}
}
Thanks for your help regardless!
EDIT:
For the sake of emphasis...
What happens:
Infinite loop spewing "phrase2".
What I wanted:
After the else is executed, I wanted to be brought into the inner loop again.
Whatever condition you're using in the inner loop, just make sure it's true.
else
{
System.out.println("phrase2");
// SET THIS TO TRUE: <condition that is false>
}
This way, the inner loop will trigger again.
Your control never enters the below if statement
if(<condition that is false>)
{
i = 1;
}
You might need to adjust your conditions so that it comes into the above if block. Introduce a System.out.println inside if statement to debug
It looks like you have some code that you probably want to run once, unless something went wrong, and then you want to go back and retry. The idiom I usually use for that looks like
boolean needToRetry;
do {
needToRetry = false;
// do whatever
if (somethingWentWrong) {
needToRetry = true;
// set this at any point where you find you will need to go back
}
} while (needToRetry);
The important thing is that you need to reset your flag (needToRetry) at the beginning of the loop, each time. (P.S. There are other ways to do this using break or continue, although I personally don't like using continue.)
So some background information, I'm new to programming and am still learning, so I apologize for my trivial error making. I am making my own text based game just to further practice etc.
Here is the link to everything on dropbox for more context:
https://www.dropbox.com/sh/uxy7vafzt3fwikf/B-FQ3VXfsR
I am currently trying to implement the combat system for my game, and I am running into the issue of the combat sequence not ending when required. The 'combat sequence' is a while loop as follows:
public void startCombat()
{
inCombat = true;
while(inCombat != false)// && herohealth > 0 && monsterhealth > 0)
{
checkAlive();
heroHitMonster();
checkAlive();
monsterHitHero();
}
attackinghero.setHeroHealth(herohealth);
attackedmonster.setMonsterHealth(monsterhealth);
}
where the checkAlive() method is as follows:
public void checkAlive()
{
if(herohealth <= 0)
{
System.out.println("You have died.");
attackinghero.clearInventory();
inCombat = false;
}
else if(monsterhealth <= 0)
{
System.out.println("You have killed the "+attackedmonster.getmonsterName()+"!");
inCombat = false;
combatlocation.removeMonster(attackedmonster.getmonsterName());
}
else
{
//
}
}
I am trying to get it to end the combat sequence when either the 'hero' or 'monster' health become <= 0,
however it is currently finishing the while loop and therefore producing the result of the hero being hit even if he killed the monster in his first hit.
This is what is currently being 'printed to screen'
rat loses 5 health!
You have killed the rat!
Hero loses 1 health!
Any help is much appreciated, thanks in advance.
checkAlive shouldn't be void it should be Boolean and should return inCombat, and in your function startCombat you should do inCombat=checkAlive();
The while loop will only evaluate after both actions. You need a way to break the loop after the hero hits the monster. I would personally change the checkAlive method to return a boolean, and put the hit methods in if statements in the while loop:
if(checkAlive())
{
heroHitMonster();
}
if(checkAlive())
{
monsterHitHero();
}
You should end the loop at the end of the checkAlive instead of changing the boolean value.
If you killed the monster at first hit, you still execute the monsterHitHero() even, if the monster is killed. The function to hit should be conditioned to the life of heroes/monster.
I've got a bit of an issue with my little program.
I have a JOptionPane asking for a number, and if that number is less than 10, a loop that just continues on and on forever doing what's in it, keeping on asking for numbers. Inside that loop, I call a method, with an int as parameter. In the method, I need to (without altering any of the code in the class that calls the method) find out whether the number I entered is less than 1. If it is, I need to call on another method. That bit's done.
But! The mainloop keeps rolling, so it keeps doing the other stuff in the loop. I need to stop it from doing that, so in the if-statement in the method I need to break that specific iteration of the loop the method is in, and make it go on to a new iteration of the same loop, asking for a new number.
The first class (example):
number=Integer.parseInt( JOptionPane.showInputDialog( "bla bla" ) );
while (number !=- 10) {
themethod(number);
blah
blah
...
}
The called method (example):
public void themethod(int number) {
if (number<1) {
call the other method
break the iteration im in
}
There are a number of things you can do here. Ultimately what you do should depend on your coding style and what you are trying to accomplish.
Option 1 would be some variation of:
for (;;)
{
int number = /* ... */;
myMethod(number);
if (number == -10)
break;
}
You might say, rather subjectively and depending on circumstances, that this is bad, because knowledge of the termination condition is contained in the loop rather than the method doing the "real work". Maybe for your loop that's OK. Maybe in other circumstances (or perhaps with other programmers? This is very much a matter of taste.) you might want to make myMethod make that decision. In general my own personal taste usually leans towards not having scenario knowledge be distributed throughout various methods in source, but in one place.
So most of what I'll write from here on will be how to make myMethod make the decision about whether or not to terminate.
Option 2 - myMethod returns a boolean indicating we should terminate:
for (;;)
{
int number = /* ... */;
if (myMethod(number))
break;
}
boolean myMethod(int number)
{
// TODO - do stuff
return number == -10;
}
But you might say that myMethod already wants to return some other type. I come from very much a C background so the idiom I'm most used to would be the "out parameter". Leading me to option 3:
Option 3 - Out parameter lets caller decide to terminate:
public class CancelIndicator
{
public boolean shouldCancel;
};
CancelIndicator cancel = new CancelIndicator();
while (!cancel.shouldCancel)
{
int number = /* ... */;
myMethod(number, cancel);
}
int myMethod(int number, CancelIndicator cancel)
{
// TODO - do stuff.
cancel.shouldCancel = (number == -10);
return /* ... */;
}
Or maybe you're more a fan of exceptions:
Option 3:
public class CancellationException extends Exception
{
}
try
{
for (;;)
{
int number = /* ... */;
myMethod(numberl);
}
}
catch (CancellationException ex)
{
}
void myMethod(int number) throws CancellationException
{
// TODO - do stuff.
if (number == -10)
throw new CancellationException();
}
As you can see there are a number of options. I'm sure one could spend a whole day talking about different ways to do it. Here is my sample of idioms I have seen - I'll warn you that it's been some time since I've done much in Java so I might not write the most idiomatic code here. :-)
Add a return value indicating that the while should break:
public boolean themethod(int number) {
if(number<1) {
call the other method
return true;
}
return false;
}
Then:
while(number !=-10) {
if(themethod(number)) break;
bla
bla
...
}
Edit: If you can't change the while code, throw an exception from the method:
public void themethod(int number) {
if(number<1) {
call the other method
throw new RuntimeException("Negative Number");
}
}
Wait, so did I get this straight? You have a loop that asks for a number, does something if the number is not -10, and otherwise breaks?
If so, look at this:
while(true) {
number=Integer.parseInt( JOptionPane.showInputDialog( "bla bla" ) );
if(number == -10) {
break;
}
themethod(number);
}
Otherwise, if this is not the case, and you want to break in two cases, the -10 case and the method is false case, you can do this:
Change your method to return a boolean. If it's true, then it doesn't want to break. If it's false then it wants to break, then do this:
while(true) {
number=Integer.parseInt( JOptionPane.showInputDialog( "bla bla" ) );
if(number == -10) {
break;
}
if(!themethod(number)) break;
}
If you really can't edit the loop, then just throw an exception from the method! That will exit your entire program, though. I don't see any other possible way of doing this, however.
Without a return value for themethod(int) and without changing the other class's code, this isn't possible since as it is, there is no return communication. You'll have to change both; it can't be done without changing the logic in the loop.