Let's say I have this:
while (a) {
while (b) {
if (b == 10) {
break;
}
}
}
Question: Will the break statement take me out of both loops or only from the inner one? Thank you.
In your example break statement will take you out of while(b) loop
while(a) {
while(b) {
if(b == 10) {
break;
}
}
// break will take you here.
}
It will break only the most immediate while loop. Using a label you can break out of both loops: take a look at this example taken from here
public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}
Only from the inner one. Use labeled break if you wish to break to specific loop
label1:
for(){
label2:
for(){
if(condition1)
break label1;//break outerloop
if(condition2)
break label2;//break innerloop
}
}
Also See
labeled break
#Abhishekkumar
Break keyword has it's derived root from C and Assembly, and Break it's sole purpose to passes control out of the compound statement i.e. Loop, Condition, Method or Procedures.
Please refer these...
http://tigcc.ticalc.org/doc/keywords.html#break
http://www.functionx.com/cpp/keywords/break.htm
http://en.wikipedia.org/wiki/Break_statement#Early_exit_from_loops
So, if you want to get out of Two loops at same time then you've to use two Breaks, i.e. one in inner loop and one in outer loop.
But you want to stop both loop at same time then you must have to use exit or return.
while (a) {
while (b) {
if (b == 10) {
break;
}
}
}
In the above code you will break the inner most loop where (ie. immediate loop) where break is used.
You can break both the loops at once using the break with label
label1:
while (a) {
while (b) {
if (b == 10) {
break label1;
}
}
}
It will break out of the loop that immediately encloses it.
You can however, break to a label:
myLabel:
while(a) {
while(b) {
if(b == 10)
break myLabel;
}
}
I don't generally like to use this pattern because it easily leads to spaghetti code. Use an unlabeled break or a flag to terminate your loop.
As a curious note, in PHP the break statement accept a numeric parameter which tells how many outer loops you want to break, like this:
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
You can raise a flag to pass the information to the outer while loop. In this case the information can be stored in a variable breakOuterLoopFlag and the outer while loop acts according to this information.
See pseudo code below:
int breakOuterLoopFlag = 0;
while(a){
while(b){
if(b == 10) {
breakOuterLoopFlag = 1;
break;
}
}
if(breakOuterLoopFlag == 1) {
break;
}
}
A break statement will take you out of the innermost loop enclosing that break statement.
In the example the inner while loop.
The java break statement won't take you out of multiple nested loops.
Only the inner loop of course.
Related
What i'm trying to do is have my code convert integers to base 2 and then turn those values into elements in a string array. I'm trying to avoid using Integer.toBinary(). If I could get some help that would be incredibly helpful.
public String[] streamChars(int[] colAvgs)
{
String avgString = Arrays.toString(colAvgs);
String convBases[] = avgString.split(",");
int remainder;
for (int a =0;a<colAvgs.length;a++)
{
remainder = colAvgs[a];
while(remainder>0)
{
remainder = remainder%2;
if ((remainder%2)==0|| (remainder%2)==1)
{
convbases[a] = Integer.toString(remainder);
a++;
}//end if
}//end while
}//end for
return convbases;
}//end streamChars
Thank you for your time!
Your remainder doesn't make it to 0 before a reaches the colAvgs value, and after that, trying to access convbases[a] crashes.
Your while should take into account that a cannot be higher or equal than colAvgs.
int size = colAvgs.length;
for (int a =0;a<size;a++)
{
remainder = colAvgs[a];
while(remainder>0 && a<size)
{
remainder = remainder%2;
if ((remainder%2)==0|| (remainder%2)==1)
{
convbases[a] = Integer.toString(remainder);
a++;
}//end if
}//end while
}//end for
if(remainder>0) //you know it finished due to a being too big.
else //this is what you want to happen
However, I think it's important to note that it's a good practice to not modify the looping variable inside a for loop, because that's part of the for's job. You should not do a++ inside the while loop. You use a for loop when you know exactly the number of iterations the loop will run. You don't have that information here. Thus, you should either change the looping condition (in this case a<size when initiating the for loop), or use a while loop instead.
Because it both uses and increases a within the while (remainder > 0) loop, without ever checking to ensure that a remains < convbases.length. (BTW, it's convbases in one place but convBases in another, which should be preventing that code from even compiling; Java is case-sensitive.)
public String[] streamChars(int[] colAvgs)
{
String avgString = Arrays.toString(colAvgs);
String convBases[] = avgString.split(",");
int remainder;
for (int a =0;a<colAvgs.length;a++)
{
remainder = colAvgs[a];
while(remainder>0)
{
remainder = remainder%2;
if ((remainder%2)==0|| (remainder%2)==1)
{
convbases[a] = Integer.toString(remainder);
// ^^^^^^^^^^^^------------------------------------- using it
a++;
// ^^^^--------------------------------------------- incrementing it
}//end if
}//end while
}//end for
return convbases;
}//end streamChars
Sorry I am having a mental block, can anyone see why I get the 'cannot convert from int to boolean' error message. Much appreciated
public static void main (String[]args) {
int max=10;
int sum=0;
int count=0;
for(int counter=0;counter=max-4;counter++) {
sum=max-4;
count=max-3;
for(sum=3;sum<5;sum++) {
if(count==0 && max>0){
System.out.println("Hello");
} else if (count<4) {
System.out.println("Go for it");
} else {
System.out.println("OK");
}
}
}
sum=sum+count;
System.out.println("Total = "+sum);
System.out.println("Max = "+count);
}
I feel like I have checked using the '==' for the if condition.
= is assignment, you need a comparison in the second term of your loop.
for(int counter=0;counter=max-4;counter++) {
should be
for (int counter = 0; counter < max - 4; counter++) {
(white space added, but note < is a comparison... perhaps you wanted <=).
In case of Java, the syntax of for loop is
for(initialization; Boolean_expression; update) {
// Statements
}
1) The initialization part executes only once when the flow enters the for loop for the first time
2) Next, the boolean expression is resolved according to the condition
3) Then next the update statement is resolved and after execution of the body of the for loop again the flow goes to the boolean expression and then update statement and the flow goes on.
So, In your program instead of a boolean expression, you have used an assignment operator which turns out to be 6 which is not 0 or 1. Boolean expression are true = 1 and false = 0. Hence the integer 6 cannot be converted to boolean. So, you can go with counter < max-4
What is the Java equivalent of the while/else in Python? Because it doesn't work in Java. The first chunk was my python code and the second portion is my attempt to translate it into Java. Edit: tring to replicate while-else
while temp.frontIsClear():
if temp.nextToABeeper():
temp.pickBeeper()
count += 1
temp.move()
else:
if temp.nextToABeeper():
temp.pickBeeper()
count += 1
print "The count is ", count
Java Attempt
Robot temp = new Robot();
int count = 0;
while (temp.frontIsClear())
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
temp.move();
}
else
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
}
print ("The count is ", count);
The closest Java equivalent is to explicitly keep track of whether you exited the loop with a break... but you don't actually have a break in your code, so using a while-else was pointless in the first place.
For Java folks (and Python folks) who don't know what Python's while-else does, an else clause on a while loop executes if the loop ends without a break. Another way to think about it is that it executes if the while condition is false, just like with an if statement.
A while-else that actually had a break:
while whatever():
if whatever_else():
break
do_stuff()
else:
finish_up()
could be translated to
boolean noBreak = true;
while (whatever()) {
if (whateverElse()) {
noBreak = false;
break;
}
doStuff();
}
if (noBreak) {
finishUp();
}
Just use one more if statement:
if (temp.nextToABeeper())
// pick beer
} else {
while (temp.frontIsClear()) { /* your code */ }
}
Or:
if (temp.frontIsClear())
while (temp.frontIsClear()) { /* your code */ }
} else if (temp.nextToABeeper()) {
// pick beer
}
If you look at the Java Backus–Naur form Grammar (Syntax Specification), else never follows a while.
Your solution needs to be modified accordingly. You can put the while in an else, that way you handle the if statement.
if temp.nextToBeeper() {
//handle
} else {
while(temp.frontIsClear()) {
//handle
}
}
Try this:
Robot temp = new Robot();
int count = 0;
if (temp.frontIsClear())
{
while (temp.frontIsClear())
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
temp.move();
}
}
else if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
print ("The count is ", count);
In Java
if is a conditional statement .
But
while is loop that is iterate again an again and stop itself when falsecondition occurred .
i have a loop which iterates equal to the length of an array, inside this loop i have a method which do some processing and have if-else structure inside. i want that if certain condition is true, then re-iterate the whole loop else continue.
the Minimum working code is provided.
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
fp.factprocess(fact, rule, vars, cons);
}
contents of fp.factprocess are like
if(condition==true)
make xx = 0 in the parent loop
else
continue
i dont know how do i do it, i used return statement but it has to be in the end and can not be in the if-block.
Return a boolean from the condition test. If boolean true, set xx to -1 (to be incremented to 0) in the loop.
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
boolean setXXtoZero = fp.factprocess(fact, rule, vars, cons);
if(setXXtoZero) xx=-1;
}
fp.factprocess:
return condition;
Yes, there can be a return statement in the if block.
public int getValue(int val){
if ( value == 5 ){
return value;
}
else{
return 6;
}
}
for instance, is valid Java code.
public int getValue(int input){
if ( input == 5 ){
return input;
}
}
on the other hand, is not, since you don't return anything if input does not equal 5, yet the method has to either return an int, or throw an Exception.
That's probably what your problem is: you need to provide a return statement for all possible scenario's.
If you want to modify the xx variable of the loop, I suggest to return a boolean in your factprocess method.
for (int xx = 0; xx < temp.length; xx++) {
rule = temp[xx][1];
cons = temp[xx][2];
boolean shouldRestart = fp.factprocess(fact, rule, vars, cons);
if (shouldRestart) {
xx = 0;
}
}
Pass xx to factprocess() and assign the return to xx
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
xx = fp.factprocess(fact, rule, vars, cons, xx);
}
Inside factprocces()
if (condition == true) {
return 0
} else {
return xx
}
This is the nested for loop I have written:
int i,j;
for(i=5;i>=1;i=i-1)
{
for(j=1;j<i+1;j++)
{
System.out.print(i);
}
}
the above code prints: 555554444333221 but I'm trying to get it to add another '2' on the end, so it should print 5555544443332212.
I've spent a while changing the operators and the numbers but I haven't managed to figure it out yet.
Just add System.out.print(2) after the outer loop:
for(i=5;i>=1;i=i-1) {
for(j=1;j<i+1;j++)
{
System.out.print(i);
}
}
System.out.print(2);
As a side note, you can define i and j inside the for definitions:
for(int i=5;i>=1;i=i-1) {
for(int j=1;j<i+1;j++) {
simply just print a 2 at the end of for loop
for(i=5;i>=1;i=i-1) {
for(j=1;j<i+1;j++)
{
System.out.print(i);
}
}
System.out.print(2);