I'm using a
while (true)
{
if (x == y)
{
break;
}
else
{
//do stuff
}
}
loop like so, the frame is just an example frame, as the actual code itself is convoluted and overly complicated that it requires a "break;" statement in multiple different areas for multiple different conditions.
My question is; Is there a way to write a loop statement without the loop checking for a condition at all? Is there a more efficient way to write an infinite loop other than while(true)?
edit: (java)
edit2:
while (a < b)
{
while (true)
{
if (c < d)
{
if (e == null)
{
//do alot of stuff
break;
}
else
{
//do something
}
}
else if (d > c)
{
if (e == null)
{
//do alot of stuff
break;
}
else
{
//do something
}
}
else if (d == c)
{
break;
}
}
a = a + 1;
}
Is there a way to write a loop statement without the loop checking for a condition at all? Is there a more efficient way to write an infinite loop other than while(true)?
You can write an infinite loop in multiple ways, but they are all equivalent. Neither is really more efficient than the others:
while (true) { ... }
do { ... } while (true);
for (;;) { ... }
Depending on the actual code, it may make sense to reverse the "break-loop-logic" into "continue-loop-logic", as in:
boolean continueLoop;
do {
continueLoop = false;
// ... do stuff ...
if ( some condition ) {
continueLoop = true;
}
// ... do stuff ...
} while (continueLoop);
For your particular example, you may move the logic for breaking in the if statement to the while condition:
while (x != y) {
// do stuff
}
In fact, if your original while loop had multiple conditions for breaking, you might be able to move them all to the while condition, e.g.
while (!cond1 && !cond2 ... ) {
// execute
}
Yes there are a lot ways you can do this. For example you can declare a variable outside a loop put a condition based on variable value and reset that variable inside a loop, hence loop will run infinitely without checking internal conditions.
Read this for examples :-
https://en.wikipedia.org/wiki/Infinite_loop
Related
I've run into a problem with my multi branch if...else statements. In the challenge question they ask us to print out a line if certain variables are true|false. My statements will only print my if statement, however they compile. I feel I'm either missing something in my if statement that allows it to continue if a statement is not true|false.
Here is what I have:
if ( isBalloon && isRed ) {
isBalloon=false;
isRed=false;
System.out.println("Not a balloon");
}
else if ( isBalloon && isRed ) {
isBalloon=true;
isRed=false;
System.out.println("Balloon");
}
Also, for clarity; when we do a multi branch statement (else if) requires variable declaration, where as (else) is just anything that makes our if statement false. Is this correct?
I think this is easiest explained by pointing out that 'else if' in java isn't a separate keyword. So it is equivalent to the following (which is harder to read but points out why your code is executed only once)
if ( isBalloon && isRed ) {
isBalloon=false;
isRed=false;
System.out.println("Not a balloon");
} else {
if ( isBalloon && isRed ) {
isBalloon=true;
isRed=false;
System.out.println("Balloon");
}
}
this is what else if really does. When your code runs it hits the first if condition and when it is correct it will run the associated block. it then doesn't process the else block. (that is the idea: only if or else runs, not both).
It looks like if / else if / else if / else has multiple blocks on the same level but secretly they are nested.
for instance
if (a) {
// case a
} else if (b) {
// case b
} else if (c) {
// case c
} else {
// otherwise:
}
is actually:
if (a) {
// case a
} else {
if (b) {
// case b
} else {
if (c) {
// case c
} else {
// otherwise
}
}
}
I have a logical problem. I will provide pseudo code since the real code isn't all that readable. I want to only enter one of the instructions, and if none of the instructions are reachable I want the function to break out from the loop.
I'm pretty new to programming so any help is appreciated.
edit: In every iteration I want to only reach one of the conditions. Since there is a loop going on for a longer time I want to be able to reach the same / other instructions for every iteration
while(true){
if(condition){ // Instruction 1
do stuff
}else{
do stuff
}
if(condition){ // Instruction 2
do stuff
}else{
do stuff
}
if(condition){ // Instruction 3
do stuff
}else{
do stuff
}
if(condition){ // Instruction 4
do stuff
}else{
do stuff
}
if(none condition){
break;
}
}
I don't think anyone's got this spot on so far so I'll throw in my understanding of what you're asking.
while(true) // keep looping
{
boolean instructionExecuted = false; // we haven't done an instruction this iteration
// Instruction 1
if(condition) {
instructionExecuted = true;
//do stuff
} else {
//do stuff
}
// Instruction 2
if(condition && !instructionExecuted) { // If we've not done an instruction,
// and we can do instruction #2
instructionExecuted = true;
//do stuff
} else if (!instructionExecuted) { // only do this if we haven't already
// done an instruction
//do stuff
}
// Instruction 3
if(condition && !instructionExecuted) { // If we've not done an instruction,
instructionExecuted = true; // and we can do instruction #3
//do stuff
} else if (!instructionExecuted) { // only do this if we haven't already
// done an instruction
//do stuff
}
//etc.
if(none condition)
{
break;
}
}
Adding a bool trigger might be what you are looking for. if you enter any if statements turn the trigger to true.
You're making this harder than it has to be. All you need to do is have an if statement with multiple else if statements after it.
Example:
if (condition) {
doStuff();
} else if (condition) {
doStuff();
} else if (condition) {
...
} else {
break;
}
well, there are multiple ways to accomplish what you want:
Introduce a top-level boolean flag doNotBreak and set true in if/else blocks execution of which means the loop should not break.
Check should it break or not by combining conditions using in the loop: if(condition1 && !condition2 && ..) break;
Instead of the last condition, break with condition and inside if/else block where you don't want to break, use continue.
boolean reachable = false;
while(true){
if(condition){ // Instruction 1
do stuff
reachable = true
}else{
do stuff
}
if(condition){ // Instruction 2
do stuff
reachable = true
}else{
do stuff
}
if(condition){ // Instruction 3
do stuff
reachable = true
}else{
do stuff
}
if(condition){ // Instruction 4
do stuff
reachable = true
}else{
do stuff
}
if(!reachable){
break;
}
}
Alternatively you can check if it is possible to use switch Statements instead of if-else. Example
public static void main(String argv[]) {
String [] conditions = {"condition_1","condition_2","condition_3","condition_4","xyz"};
printConditionType(conditions);
}
public static void printConditionType(String [] conditions){
int i = 0;
while (i<conditions.length){
switch (conditions[i]) {
case "condition_1":
System.out.println("#1");
break;
case "condition_2":
System.out.println("#2");
break;
case "condition_3":
System.out.println("#3");
break;
case "condition_4":
System.out.println("#4");
break;
default:
System.out.println("Invalid condition:" + conditions[i]);
}
i++;
}
}
This might be a stupid question but we're beginners and I didn't find an answer to my problem so here it is: We're developping a file system (small based) and we have this method that is supposed to move files from one Directory to another. (Deleting the file or directory from one and adding to another.)
We're using ArrayLists to store the Items (Item is then superclass of Directory and File).
Because of the fact that everything has to be sorted alphabetically, the method to move contains a while loop to verify where the item has to be placed (no preferences to Directories or Files) but for some reason the break statement I inserted is ALWAYS executed (or at least that's what I think is the reason.) Thanks!
Here's the code:
if(item != null){
boolean bool = false;
int i = 0;
loop: while(!bool && i <= items.size()-1) {
if(i==0) {
if(checkIfAlphabetic(item.getName(), items.get(0).getName())){ items.add(0,item);
bool = true;
}
else{
break loop;
}
}
else if(checkIfAlphabetic(items.get(i-1).getName(), item.getName()) && checkIfAlphabetic(item.getName(), items.get(i).getName() )) {
items.add(i, item);
bool = true;
}
else i++;
}
if(!bool){
items.add(item);
}
setModificationTime();
}
I already excuse myself if there are some things unclear.
PS. Also for some reason the Item I want to add always gets added twice.
As requested, the code for checkIfAlphabetic:
private boolean checkIfAlphabetic(String search, String target){
int[] searchInt = search.codePoints().toArray();
int[] targetInt = target.codePoints().toArray();
int i = 0;
while(i<search.length() && i<target.length()){
if(searchInt[i] > targetInt[i]){
return false;
}
else if(searchInt[i] < targetInt[i]) return true;
else i++;
}
if(search.length() < target.length()){
return true;
}
else return false;
}
Your while loop is faulty. It will always stop after the first iteration, no matter what.
This is what happens in order of statements. This is pseudo-code, not Java. Don't copy/paste, it won't work.
boolean bool = false;
int i = 0;
// entering the while loop:
if (!bool && i <= items.size() - 1) // returns true. We go in the while loop.
if (i == 0) // returns true, we go in that block.
if (check... ) // if this returns true, this happens:
bool = true;
else // if the previous statement returns false, this happens:
break;
So here, if the check... returns false, we're gonna get out of the loop. Let's continue in the other case:
// nothing else happens inside the loop, so go back to the loop condition.
if (!bool && i <= items.size() - 1) // Hey, wait a minute, bool is true. So "not" true is false. The condition is therefore not met, let's leave the loop.
So this is what happens, after a single execution, no matter what, your code exits the loop. In your scenario, bool = true is the near absolute equivalent to a break.
This is what you need to fix.
If I had to write your code, this is how I'd do it:
List<Item> items = ... ;
java.util.Collections.sort(items, new ItemNameComparator());
private static class ItemNameComparator implements Comparator<Item> {
#Override
public int compare(Item a, Item b) {
return a.getName().compareTo(b.getName());
}
}
If you use Java 8:
List<Item> items = ...;
items.sort((a, b) -> a.getName().compareTo(b.getName()));
All the tools exist in the Java libraries, use them instead of reimplementing them again and again.
For the purpose of my question I've only included case 1, but the other cases are the same. Let's say value is currently 1, we go to case 1 and our for loop goes through the array to see if each element matches with the whatever_value variable. In this case if it does, we declare the value variable to be equal to 2, and we break out of the loop. The problem is that when i highlight the other break(in eclipse), it says that the breaks are attached to the for statement as well, but i only wanted the for statement to be attached to the if statement, not the else if statements as well. I thought because there are no brackets for the for statement that it would only loop for the if statement but eclipse says otherwise(else if also loops from 0 to the length of the array).
switch (value) {
case 1:
for (int i = 0; i < something_in_the_array.length; i++)
if (whatever_value == (something_in_the_array[i])) {
value = 2;
break;
} else if (whatever_value == 2) {
value = 3;
break;
} else if (whatever_value == 3) {
value = 4;
break;
}
break;
case 2:
// code continues....
Your problem..... I think is that your for loop is encompassing all of the if, else if stuff - which acts like one statement, like hoang nguyen pointed out.
Change to this. Note the brackets that denote the code block on which the for loop operates and the change of the first else if to if.
switch(value){
case 1:
for(int i=0; i<something_in_the_array.length;i++) {
if(whatever_value==(something_in_the_array[i])) {
value=2;
break;
}
}
if(whatever_value==2) {
value=3;
break;
}
else if(whatever_value==3) {
value=4;
break;
}
break;
case 2:
code continues....
In this case, I'd recommend using break labels.
http://www.java-examples.com/break-statement
This way you can specifically call it outside of the for loop.
Seems like kind of a homely way of doing things, but if you must...
you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
If you need the for statement to contain only the if, you need to remove its else, like this:
for(int i=0; i<something_in_the_array.length;i++)
if(whatever_value==(something_in_the_array[i]))
{
value=2;
break;
}
/*this "else" must go*/
if(whatever_value==2)
{
value=3;
break;
}
else if(whatever_value==3)
{
value=4;
break;
}
but i only wanted the for statement to be attached to the if statement, not the else if statements as well.
Well get rid of the else then. If the else if is not supposed to be part of the for then write it as:
for(int i=0; i<something_in_the_array.length;i++)
if(whatever_value==(something_in_the_array[i]))
{
value=2;
break;
}
if(whatever_value==2)
{
value=3;
break; // redundant now
}
else if(whatever_value==3)
{
value=4;
break; // redundant now
}
Having said that:
it is not at all clear what you are really trying to do here,
not having the else part in the loop doesn't seem to make a lot of sense here,
a lot of people (myself included) think it is to always use braces ... so that people don't get tripped up by incorrect indentation when reading your code. (And in this case, it might help us figure out what you are really trying to do here ...)
Finally, braces are less obtrusive if you put the opening brace on the end of the previous line; e.g.
if (something) {
doSomething();
}
rather than:
if (something)
{
doSomething();
}
How can i do forward jumps like this?? Eclipse is complaining label1 is not found...
Thx
public class foo {
int xyz() {
int b = 1;
if (b == 0) {
break label1;
}
// MORE CODE HERE
label1:
return 1;
}
}
You are trying to use the equivalent of goto in Java. You can't, and for good reason. Abandon ship.
Labels are included in Java for the sole reason of choosing which loop or switch to break out of, in the case of nested loops (or switch statements). They have no other purpose, and even that single purpose is often considered dangerously close to a goto.
Labels are only applicable to loops (and blocks in general). And you are trying to mimic a goto. Don't.
You can't do that. You can only break out of an enclosing loop structure. You don't have a loop structure at all. Try this instead:
public class foo {
int xyz() {
int b = 1;
boolean skip = false;
if (b == 0) {
skip = true;
}
if (!skip) {
// MORE CODE HERE
}
return 1;
}
}
I addition to the previous answers, why not just
if (b == 0) {
return 1;
}
?