Here is the structure of my program:
for(loop1){
if(condition1)
{
for(loop2)
{
for(loop3)
{
if(condition1_3)
{
As condition1_3 is true continue with loop2's next iteration,
No need to execute loop3's remaining iteration
}
else
{
As condition1_3 is false no need to execute remaining part of loop3 and
loop 2 but continue with loop1's remaining part i.e. condition1_1
}
}
}
}
if(condition1_1)
{
some code here
}
}
I know I have to use continue and break statement but don't understand exactly how?
Please tell me how to achieve this mechanism?
If I understand your question, you could use the labeled continue,
loop1: for (;;) {
if (condition1) {
loop2: for (;;) {
loop3: for (;;) {
if (condition1_3) {
continue loop2;
} else {
continue loop1;
}
}
}
}
}
You can do as follows:
for(loop1){
if(condition1)
{
for(loop2)
{
boolean flag=false;
for(loop3)
{
if(condition1_3)
{
break;
}
else
{
flag=true;
break;
}
}
if(flag)
break;
}
}
if(condition1_1)
{
some code here
}
}
Do like the following -
for(loop1){
boolean flag = false;
if(condition1)
{
for(loop2)
{
if(flag == true)
break;
for(loop3)
{
if(condition1_3)
{
break;
}
else
{
flag = true;
break;
}
}
}
}
if(condition1_1)
{
some code here
}
}
An option would be to use variables - but you have to think about correct setting of values:
boolean runFor1 = true;
boolean runFor2 = true;
boolean runFor3 = true;
for(loop1 && runFor1)
{
for(loop2 && runFor2)
{
for(loop3 && runFor3)
{
setRunForX here to skip/unskip loops
}
}
}
}
Have a exit flags which is set when you want to exit a particular loop and check in each respective loops whether to continue or exit.
boolean exitLoop2 = false;
for(loop1){
if(condition1)
{
for(loop2)
{
for(loop3)
{
if(condition1_3)
{
//As condition1_3 is true continue with loop2's next iteration,
//No need to execute loop3's remaining iteration
break;
}
else
{
//As condition1_3 is false no need to execute remaining part of loop3 and
//loop 2 but continue with loop1's remaining part i.e. condition1_1
exitLoop2 = true;
break;
}
}
if(exitLoop2)
{
break;
}
}
}
if(condition1_1)
{
some code here
}
}
To break out and not continue the loop3 use break; if (condition1_3) break; The break; statement only breaks out of the current loop i think, not the loop it is nested in.
Edit: Missread the question
To break out of both loops you can make a boolean flag before both loops and at the end of both loops have an if (breakOut) break; This will solv the question
I'm not really shure what do you mean exactly. For me it simply looks like you want to jump out of the loops if a specific condition is satisfied. So you can either can define a label for your loops and use the continue labelLoopX; statement or you can satisfy the exit condition of loop3 if condition1_3==true resp. the exit condition of loop3 and loop2 if condition1_3==false. e.g. if loop3 looks like for ( int i = 0; i < 10; i++ ) like this:
if(condition1_3){
//do something important
i=10; //sets i to 10 and condition i < 10 is unsatified
}
else{
//do some other important stuff
i=10; //satify loop3's exitcondition
j=10; //satify loop2's exitcondition
}
Related
Recently, I tried to write a Java program which searches for the minimum of an array.
I tried to write it in a different way, I know there are more simple ways to do that but I want to know why my program does not work.
Here is the source code :
public int minimum(int [] t) {
int min,i,j;
i=j=t.length/2;
min=t[t.length/2];
while(j!=0 || i!=t.length-1) {
while( t[i]>=min) {
i++;
if(i==t.length) {
i=t.length-1;
continue;
}
}
while(t[j]>=min) {
j--;
if(j==-1) {
j=0;
continue;
}
}
if(t[i]<=min && t[j]<=min) {
if(t[i]<=t[j]) min=t[i];
else min=t[j];
}
}
return min;
}
Thanks.
Before you read the answer you should try debugging your code to figure this out by yourself.
I think your code loops infinitely in one of those inner while loops because the end condition
if(i==t.length) {
i=t.length-1;
continue;
}
only resets the i one step back and the continue restarts the while loop. You probably meant to have the break keyword there instead of the continue in which case your code will continue with the other inner while loop.
there is some logic errors in my code , and it get infinitely going through the two loops , i fixed the loops by changing continue with break and i modify the last condition by setting || instead of && (that was a logic mistake), and it works now .
thanks guys.
here is the new source code:
public int minimum(int [] t) {
int min,i,j;
i=j=t.length/2;
min=t[t.length/2];
while(j!=0 || i!=t.length-1) {
while( t[i]>=min) {
i++;
if(i==t.length) {
i=t.length-1;
break;
}
}
while(t[j]>=min) {
j--;
if(j==-1) {
j=0;
break;
}
}
if(t[i]<=min || t[j]<=min) {
if(t[i]<=t[j]) min=t[i];
else min=t[j];
}
}
return min;
}
I would like to break a while loop only when all of the "bots" are upright. (*These bots being referred to are mini USB robots).
.upRight() returns true when a bot is standing and false when not.
public static boolean checkSomething() throws ... {
while (true) {
for (i = 0; i < bots; i++) { // bots = 2
if (!theMainBots[i].isUpright()) {
...
Thread.sleep(1000);
}
else {
return true;
}
}
}
The issue I'm facing, is that if the isUpright() method returns true for the first "bot", then all other bots are left unchecked and may return false. The intention is to wait for the user to place the bot in an upright position before proceeding.
You should check all the bots first, then act on the result. Don't try to act on the result inside the check loop.
Also, since the code doesn't return until all bots are upright, the method is misnamed and shouldn't return a value.
public static void waitUntilAllUpright() throws InterruptedException {
for (;;) { // forever loop
boolean allUpright = true;
for (i = 0; i < bots; i++) {
if (! theBots[i].isUpright()) {
allUpright = false;
break;
}
}
if (allUpright)
return;
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
} // loop back to check all bots again
}
If you want to wait until the user makes the bot upright you could change the if to a while:
while (true) {
for (i = 0; i < bots; i++) { // bots = 2
while(!theBots[i].isUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
}
}
return true;
}
This will loop through each element in the Array and while any given bot is not upright, it will loop and sleep until the bot is turned upright. In which case, you do not need to while(true) loop:
public static boolean checkUpright() throws InterruptedException {
for (i = 0; i < bots; i++) { // bots = 2
while(!theBots[i].isUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
}
}
return true;
}
One way to achieve this, is using a variable that will determine when to leave the loop. Your problem here, is that you also need to change your for loop for a while loop. Why is that? Because you don't know if the bot you just checked was moved or not. Also, the outer loop is unnecessarily, unless you wanted to recheck again. So the code would end looking something like this.
public static boolean checkUpright() throws InterruptedException {
int counter = 0;
while (counter <= theBots.length) { // bots = 2
if (!theBots[i].isUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
} else {
counter ++;
}
}
}
The context is not completely clear, but mixing logical control with user interaction might be the problem. Perhaps this approach might work:
public static boolean checkUpright() throws InterruptedException {
while (!areAllBotsUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
}
}
public static boolean areAllBotsUpright() {
for (i = 0; i < bots; i++) {
if (!theBots[i].isUpright()) {
return false;
}
}
return true;
}
you can create a list from array of bots , iterate over this list using iterator
if a particular bot is upright , remove it from this list using iterator.remove.
outer while will run until list is not empty.
public static boolean checkUpright() {
ArrayList<Bot> notUprightBots= (ArrayList<Bot>) Arrays.asList(theBots);
while (!notUprightBots.isEmpty()) {
Iterator<Bot> iterator=notUprightBots.iterator();
while(iterator.hasNext()){
Bot bot=iterator.next();
if (!bot.isUpright()) {
System.out.println("Please ensure I'm upright");
try{
Thread.sleep(500);
}catch(InterruptedException e){
}
}else {
iterator.remove();
}
}
}
return true;
}
I have a for loop similar to the one given below.
for(int i=0; i<10; i++)
{
boolean condition = checkCondition(); /* line 3 */
if(condition)
{
if(some other condition A)
{
move to line 3;
}
else if(some other condition B)
{
call_method_B();
}
else
{
call_method_C();
}
}
else
{
call_method_D();
}
}
How do I make the program go back to line 3 within the if statement as above? I don't want to break the iteration. Needs to be in the same iteration and only need move back to line 3.
to be in the same iteration, just subtract i by 1 before you call continue.
do note that this will get you into an infinite loop if the condition is never changed.
for(int i=0; i<10; i++)
{
boolean condition = checkCondition(); /* line 3 */
if(condition)
{
if(some other condition A)
{
move to line 3;
i--; //this will cancel out the i++ in the for loop
continue; //this will bring you back to line 3
}
... the rest of your codes
I don't want to break the iteration. Needs to be in the same iteration and only need move back to line 3.
I think you need a while loop. Then you have more control over when you iterate. When you get the conditionA check, then i doesn't change, and the loop repeats, otherwise you can say i++.
int i = 0;
while (i < 10) {
if (checkCondition()) {
if (some other condition A) {
// continue the iteration
} else if (some other condition B) {
call_method_B();
i++;
} else {
call_method_C();
i++;
}
} else {
call_method_D();
i++;
}
}
I believe your problem seems to need a recursive approach instead of an iterative approach.
The above problem can be solved using a recursive approach in the following way:
public void checkRecursive()
{
boolean condition = checkCondition();
if (base_condition_to_avoid_recursion)
return;
if (condition)
{
if (some other condition A)
{
checkRecursive();
}
else if (some other condition B)
{
call_method_B();
}
else
{
call_method_C();
}
}
else
{
call_method_D();
}
}
int i = 1;
while(i == 1) {
if (answerHold.equals(generate)) {
qgCharacter();
i++;
} else if (answerHold.equals(create)) {
qcCharacter();
i++;
}
}
The above code keeps running until a desired value is entered.
How would I maintain the accessibility of the variable inside of the while loop, instead of the variable having to be outside of the loop?
Would using a different loop make more in sense in this situation?
Use the "break" keyword instead of changing the value of "i".
while(true) {
if (answerHold.equals(generate)) {
qgCharacter();
break;
} else if (answerHold.equals(create)) {
qcCharacter();
break;
}
}
The following construct would make more sense in my opinion. Without a variable!
while (true) {
if (answerHold.equals(generate)) {
qgCharacter();
break;
} else if (answerHold.equals(create)) {
qcCharacter();
break;
}
}
Just a quick question, can i use this to include "left" "right"
back" and "forward" all together or do i have to do them separately?
An error came up, so if anyone knows how to include them all together then please help. Thanks
Scanner console = new Scanner(System.in);
for (int i = 0; i < 100; i++) {
System.out.println("Please type in either the word \"left\" or \"right\" or \"back\" or \"foward\": ");
String s = console.next();
if (s.equalsIgnoreCase("left")) {
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(0,100,S);
} if (s.equalsIgnoreCase("right")) {
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(100,0,S);
} if (s.equalsIgnoreCase("back")) {
myFinch.setWheelVelocities(-100,-100,S);
} if (s.equalsIgnoreCase("foward")) {
myFinch.setWheelVelocities(130,130,S);
} else if (s.equalsIgnoreCase != ("left" && "right" && "back" && "foward")) {
myFinch.quit();
}
I would go with a switch statement :
switch (s.toLowerCase()) {
case "left":
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(0,100,S);
break;
case "right":
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(100,0,S);
break;
}
First off to answer your question, in Java you should use String.equals to compare strings, or String.equalsIgnoreCase. This is because this example will fail:
String a = "a";
if (a == "a") {
// Will not be true because you are comparing the reference to the string "a"
} else if (a.equals("a")) {
// Will work because you are comparing on the value of the two strings
}
ref: == vs .equals
I noticed you did this in the first few statements, but on the last statement, the one in question, you did not.
While the statement you were trying to form was not necessary I find it would be useful to share the correct way to do it:
// OMITTED CODE
} else if (s.equalsIgnoreCase("left") && s.equalsIgnoreCase("right") && s.equalsIgnoreCase("back") && s.equalsIgnoreCase("foward") ) {
myFinch.quit();
}
You must make each boolean statement complete, in the sense that it must evaulate to a boolean.
s.equalsIgnoreCase != x// this is simply method so it could not be compared to anything using the != operator
("left" && "right" /* etc */ ) // "left", "right" are not booleans but simply strings.
Java is a very explicit language so shortcuts as the one you attempted are often far and few between.
Secondly you should use the format:
if (/* condition 1*/) {
// code if condition 1 is true
} else if (/* condtion 2 */) {
// code if condition 2 is true but condition 1 is false
} else {
// code if condition 1 and condition 2 are false
}
The else if statement is used to simplify code that would take the following format:
if (/* condition */) {
// code will run if condtion is true
} else {
if (/* sub-condition */) {
// code will run if sub-condition is true, but condition is false
} else {
if (/* sub-sub-condition */) {
// code will run if sub-sub-condition is true, but sub-condition and condition are false
} else {
// code will run if condition, sub-sub-condition, and sub-condition is false
}
}
}
To avoid long chains of such code:
if (/* condition */) {
// code will run if condtion is true
} else { if (/* sub-condition */) {
// code will run if sub-condition is true, but condition is false
} else { if (/* sub-sub-condition */) {
// code will run if sub-sub-condition is true, but sub-condition and condition are false
} else {
// code will run if condition, sub-sub-condition, and sub-condition is false
}}}
The formatting can be seen clearly from here to the current setup:
if (/* condition */) {
// code will run if condtion is true
} else if (/* sub-condition */) {
// code will run if sub-condition is true, but condition is false
} else if (/* sub-sub-condition */) {
// code will run if sub-sub-condition is true, but sub-condition and condition are false
} else {
// code will run if condition, sub-sub-condition, and sub-condition is false
}
These statements were created to read in a logical way:
If the first condtion is met follow the first set of instructions,
else if the first condition wasnt met then try the second condition and instructions,
else if the first two conditions failed try the third set!,
else Damn! Just resort to these instructions
Imagine a scenario where you are taking care of your friend's cat. You are unable to talk about how to care for the cat before your friend leaves but they left you a set of instructions:
Dear friend,
Thank you for looking after muffins. She is a very high maintenance cat.
She has four kinds of food and depending on her mood you should feed her one of
these four: "Purina Super Awesome Cat Time", "Cat Feast 2000", "Cat Chow", and
"Canned".
If you come over and she is waiting at the door give her the "Cat Fest 2000",
If she is not waiting at the door, but instead attacks your leg as you enter the
house you should give her the "Cat Chow",
If she is not at the door, and didn't attack you but is instead wearing a small hat
you should give her the "Purina Super Awesome Cat Time" and play a game of Bridge with
her.
If none of those things happened then give her the "Canned".
Thanks! See you Caturday!
Instead of sending yourself on this monstrous task, with clearly outlined danger, perhaps we want to write a very intelligent robot to go in and take care of the cat each day.
// Upon arrival
if ( Cat.isWaitingAtTheDoor() ) {
Cat.feed("Cat Fest 2000");
} else if ( Cat.didAttackWhenYouWalkedIn() ) {
Cat.feed("Cat Chow");
} else if ( Cat.isWearingSmallHat() ) {
Cat.feed("Purina Super Awesome Cat Time");
Cat.playBridgeWith(self);
} else {
Cat.feed("Canned");
}
So reformat your code to match that structure and you will find you don't need that last condition:
Scanner console = new Scanner(System.in);
for (int i = 0; i < 100; i++) {
System.out.println("Please type in either the word \"left\" or \"right\" or \"back\" or \"foward\": ");
String s = console.next();
if (s.equalsIgnoreCase("left")) {
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(0,100,S);
} else if (s.equalsIgnoreCase("right")) {
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(100,0,S);
} else if (s.equalsIgnoreCase("back")) {
myFinch.setWheelVelocities(-100,-100,S);
} else if (s.equalsIgnoreCase("foward")) {
myFinch.setWheelVelocities(130,130,S);
} else {
myFinch.quit();
}
}
The way you had it set up initially you essentially are not creating a branch structure.
consider this:
int i = 0;
if (i == 0) {
System.out.println("i = 0");
i = 1;
} if (i == 1) {
System.out.println("i = 1");
} else {
System.out.println("i is neither 1 or 0");
}
This will out put:
i = 0
i = 1
Not what we intended!
This is because the above code is equivalent to:
int i = 0;
if (i == 0) {
System.out.println("i = 0");
i = 1;
}
// Two separate statements altogether
if (i == 1) {
System.out.println("i = 1");
} else {
System.out.println("i is neither 1 or 0");
}
Whereas:
int i = 0;
if (i == 0) {
System.out.println("i = 0");
i = 1;
} else if (i == 1) {
System.out.println("i = 1");
} else {
System.out.println("i is neither 1 or 0");
}
Will give:
i = 0
What we wanted, now it is a branched statement, it checks the first if statement then all else if statements following and lastly if none were true resorts the else statement. This seems to be your intention since there is no space for variab;e reassignment between these if statements.
Since JDK 7 you can use strings in switches.
Means:
switch(s.toLowerCase()) {
case "left":
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(0,100,S);
break;
case "right":
myFinch.setWheelVelocities(90,90,S);
myFinch.setWheelVelocities(100,0,S);
break;
case 'back':
myFinch.setWheelVelocities(-100,-100,S);
break;
case "foward"
myFinch.setWheelVelocities(130,130,S);
break;
/** .. and other cases **/
default:
myFinch.quit();
}