How to break from a loop after the condition is met - java

Hi I have been trying for the past hour to break from this loop and continue since already met my condition once. My application pretty much reads a serie of lines and analyzes it and then prints the variable stated. An example of how the lines look like (the . are not included):
10 c = 9+3
20 a = c+1
30 print c
40 goto 20
50 end
It does everything right, when it gets to line 40 goes to line 20 as expected, but i want it to go to line 50 since already went to line 40 once. Here is my code for this part:
while(booleanValue)
{
if(aString.substring(0, 4).equals("goto"))
{
int chosenLine = Integer.parseInt(b.substring(5));
if(inTheVector.contains(chosenLine))
{
analizeCommands(inTheVector.indexOf(chosenLine));
i++;
}
else
{
System.ou.println("Line Was Not Found");
i++;
}
}
else if(aString.substring(0, 3).equals("end"))
{
System.out.println("Application Ended");
booleanValue = false;
}
}

Use the break statement to break out of a loop completely once your condition has been met. Pol0nium's suggestion to use continue would not be correct since that stops the current iteration of the loop only.
while(foo)
{
if(baz)
{
// Do something
}
else
{
// exit condition met
break;
}
}
All this having been said, good form dictates that you want clean entry and exit points so that an observer (maybe yourself, revisiting the code at a later date) can easily follow its flow. Consider altering the boolean that controls the while loop itself.
while(foo)
{
if(baz)
{
// Do something
}
else
{
// Do something else
foo = false;
}
}
If, for some reason, you can't touch the boolean that controls the while loop, you need only compound the condition with a flag specifically to control your while:
while(foo && bar)
{
if(baz)
{
// Do something
}
else
{
// Do something else
bar = false;
}
}

You could keep the code using booleanValue as-is and switch to a do-while loop.
do {
// ... existing code
} while (booleanValue);
However, to answer your specific question - you can always use the java break keyword. The continue keyword is more for skipping the remainder of the loop block and entering another loop iteration.
if you put this before your check for anything else, you would exit the loop immediately.
if(aString.substring(0, 3).equals("end")) {
break;
}
As an additional tip, you may want to use String.contains("end") or String.endsWith("end") instead of substring(). This way if a 1 or 3 digit (or more) number is used your code will still work.

Related

Can you help me what's wrong with all the phrase behind while-if-break?

public class Main{
public static void main(String[] args) {
int n=0;
while(n<10) {
if(n<5) {
continue;
}
else {
break;
}
System.out.println(n); n++;
}
}
}
here, I think while can continue to run after if but compile error all phrase behind else-break!
like System.out.println(n); n++;
System.out.println(n); n++; is unreachable because both the if and the else blocks either exit the loop or jump to the next iteration.
continue will cause the loop to immediately go back to the start, skipping the rest of the code in the loop.
break will immediately exit the loop and continuing execution after it. Therefore, it also skips the rest of the loop body.
If you get an error and ask a question on Stackoverflow, please always post the error output or your console (could also be a screenshot pasted as image).
Reproducing your example showed following compiler error:
Main.java:18: error: unreachable statement
System.out.println(n); n++;
Now you and we can start analysing, or even spot the error directly:
Compiler error explained
Here (line 18) unreachable statement means that System.out.println(n); will never be reached. This is because the previous if-statement already terminates the current iteration of your loop. It either breaks or continues:
if (n < 5) {
continue;
} else {
break;
}
Analysis of the code
From your code I assume, that you want to loop exactly 5 times (iterations), from n=0 to n=4. Like in this quick-fixed demo.
But in your case the counter variable n will never be increased, because n++ after the println is also never reached. So the program would be stuck in an infinite loop. Good that the compiler warned you.
Solution
Here's how you could fix at first:
Move the println(n) and n++ to print the counter for each iteration and afterwards increase directly, before the if (5 lines on console).
Invert the if statement to test for n >= 5 and break then
Remove the else and it's consequence continue
The else .. continue is obsolete, because a loop will always continue with the next iteration.
Ask yourself: Why should it break on the 6th iteration (when n=5) ?
int n=0;
while (n < 10) {
System.out.println(n); // starts with 0 and will reach until 9
n++;
if (n >= 5) { // n starts with 1 and breaks starting with 5
break;
}
System.out.println("What should happen here? n=" + n); // because it will reach here from 1 to 4
}
Test this solution on IDEone.
Not sure if this does what you wanted.
Please update your question and tell us your requirement (what you expected/wanted to achieve)!

LibGDX Do Something One Time During Update Method

I'm a bit new to Java and LibGDX, and I'm working on a point based game. A problem I'm facing is that the update method constantly runs something that I want to run on a timely manner. In my update method, I have the code to increment the score if a point is earned, and to make a lose state come up when the player lost. Without going into much detail, here's the pseudo code I have:
protected void update(float dt){
for(Thing x : a list) {
x.update(dt);
//continue
if (you complete the objective of the game) {
score++;
//do other stuff
}
//lost
if (you fail to complete the objective){
make lose state come up
}
}
//I want something like this to run:
if(score >=0 && score <=10){
do something ONCE(ie. print to console once)
}
if(score >= 11 && score <=15){
do something once
}
if(ect...){
do something else once
}
.
.
.
The problem here is that, if the IF condition is met, I notice the IF block gets executed multiple times very quickly(ie. printing to the console a lot). I have enclosed the details of the code that relies on the score in a separate class, I just want to be able to call the method from this update method and have it run once depending on the score conditions (ie. run it again if the score satisfies another IF statement)
I had the same problem, but I solved it by using following method. In Libgdx the update method runs in 1/60 second. That is the reason the method is rendering continously and the if condition will be executing various times.
To solve this problem, just declare an integer variable, say count, in your create method.
public static int count;
public static void create()
{
count =0;
// do other stuffs
}
protected void update(float dt){
// just increment this count value in your update method
for(Thing x : a list) {
count++
x.update(dt);
//continue
if (you complete the objective of the game) {
score++;
//do other stuff
}
//lost
if (you fail to complete the objective){
make lose state come up
}
}
// and make a small condition to run the if condition only once by using the declared variable "count".
if(count%60==0){
// here the condition only executes when the count%60==0.that is only once in 1/60 frames.
if(score >=0 && score <=10){
}
if(score >= 11 && score <=15){
}
if(ect...){
}
}
.
.
. This is how I solved the same issue.
The update() method is called every frame, multiple times very quickly(usually 60 times per second) in an infinite loop. This is not only specific in libGDX, but in any game engine. And when some condition of your if block evaluates to true, that if block is executed every frame until that condition becomes false again. But you want to execute the block only once after the condition changed.
Just declare a variable named isLastScoreUnder10 or whatever, and update it after the if block. Like this:
private boolean isLastScoreUnder10 = false;
protected void update(float dt){
if(!isLastScoreUnder10 && score >=0 && score <=10){
isLastScoreUnder10 = true;
// ..do something
} else {
isLastScoreUnder10 = false;
}
}

Modify while loop to execute at-least once

doing some exam revision. One question is, Modifiy code to so that the loop will execute at-least once.
My Code :
int x = 0;
while (x < 10) {
if (x % 2 != 0) {
System.out.println(x);
}
x++;
}
Now i know while will loop while the condition is true, i know i cannot remove the x++ as this will give me infinite zeros. i think i would just remove the if statement and the brace related to it.
would you agree?
int x = 0;
while (x < 10) {
System.out.println(x);
x++;
}
Although this specific loop actually executes at least once even unchanged, that is not a property of a while-loop.
If the condition in the while-loop is not met, the loop never executes.
A do-while loop works almost the same way, except the condition is evaluated after execution of the loop, hence, the loop always executes at least once:
void Foo(bool someCondition)
{
while (someCondition)
{
// code here is never executed if someCondition is FALSE
}
}
on the other hand:
void Foo(bool someCondition)
{
do
{
// code here is executed whatever the value of someCondition
}
while (someCondition) // but the loop is only executed *again* if someCondition is TRUE
}
I would not agree, that would change the fundamental purpose of the loop (to emit every other number to stdout).
Look into converting to the do/while loop.
Whilst your solution has technically answered the question, I don't think it's what they were looking for (which isn't really your fault, and makes it a badly-worded question in my opinion). Given it's an exam question, I think what they're after here is a do while loop.
It works the same as a while loop except that the while condition is checked at the end of the loop - which means that it will always execute at least once.
Example:
while(condition){
foo();
}
Here, condition is checked first, and then if condition is true, the loop is executed, and foo() is called.
Whereas here:
do{
foo();
}while(condition)
the loop is executed once, foo() is called, and then condition is checked to know whether to execute the loop again.
More:
For further reading you might want to check out this or this tutorial on while, do while and for loops.
int x = 0;
while (x <10){
System.out.println(x);
x++;
}
Will work
EDIT: i think the others comments are rights too, the do/while loop will force one execution of the code
var x = 0;
do {
if (x % 2 != 0) System.out.println(x);
x++;
} while (x < 10);

Java Android For statement/loop parameters

Hello i've aquired some java code from an android sample project online and in the code there is a For statement/loop. The parameters for this For statement are displayed as (;;) rather than something like (int i = 0; i < string; i++). Can anyone explain exactly what this loop is doing by having the parameters as (;;)? i've tried researching online but can't find a thing!
thanks
for (;;) {
len = mSerial.read(rbuf);
rbuf[len] = 0;
if (len > 0) {
//do something
}
}
for (;;)
is an infinite for loop as there is no exit condition.
For loop syntax
for(initialization; Boolean_expression; update)
{
//body
}
initialization,Boolean_expression,update, body: all of them are optional. The for loop keep executing until Boolean_expression till it is not false. If Boolean_expression is missing then for loop will never terminate.
no initialisation, no exit condition, no increment.. it is a infinite loop?
It is an infinite loop. A for loop has 4 parts
for (initialisation; condition; increment/decrement) {
loop body
}
You may choose to omit any of these parts (although some compilers may complain about the lack of a loop body and others will omit the entire loop for performance).
It is perfectly feasible that you may already have a variable initialised, and may skip the initialisation within the loop:
int i = 0;
for ( ; i < 10; i++ ) {
// do something
}
It is also possible that you can choose to omit the incrementation, and do it elsewhere (be careful to include it inside the loop, otherwise this may lead to infinite loops unintentionally):
for ( int i = 0; i < 10; ) {
// do something
i++;
}
It is also possible to omit the conditional and include that elsewhere:
for ( int i = 0; ; i++ ) {
// do something
if (i == 9) {
break;
}
}
Or you can omit all of it entirely and make an infinite loop.
It is an infinite loop that does something when the if condition is satisfied. It can be used if you are waiting for an input from the user untill then it loops foreever.
When you declare for loop for (;;) .Every time loop will check the condition always it will return true so it goes in infinite loop.it is similar to while(true).if you want to break the loop then yo need to add break statement then it will come out from infinite loop.

what does "do" do here? (java)

I saw this bit of code on the interents somewhere. I'm wondering what the do is for.
public class LoopControl {
public static void main(String[] args) {
int count = 0;
do {
if (count % 2 == 0) {
for (int j = 0; j < count; j++) {
System.out.print(j+1);
if (j < count-1) {
System.out.print(", ");
}
}
System.out.println();
}
count++;
}
while (count <= 5);
}
}
By which I mean what exactly does do mean? What's its function? Any other information would be useful, too.
It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.
Sun tutorial on while and do-while.
Oh, and in this case it will print:
1, 2
1, 2, 3, 4
Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.
It is similar to a while loop, with the only difference being that it is executed at least once.
Why? Because the while condition is only evaluated after the do block.
Why is it useful? Consider, for example, a game menu. First, you want to show the menu (the do block), and then, you want to keep showing the menu until someone chooses the exit option, which would be the while stop condition.
It's a while loop that gets executed at least once.
Edit: The while and do-while Statements
do { ... } while(CONDITION) ensures that the block inside do will be executed at least once even if the condition is not satisfied, on the other hand a while statment will never execute if the condition is not met
It goes with the while. do { ... } while() is a loop that has the conditon in the end.

Categories