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;
}
?
Related
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
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?
I have some code that I would like to make more efficient by recursion. Trouble is I don't know where to start. The code compares two arraylists a and b to see if they are equal. Assume the sizes of both arrays are equal.
The code is
public boolean isEqual(A B) {
boolean answer = false;
if (lessThanOrEqualTo(B) == true);
for (int i = 0; i < DList.size(); i++) {
if (DList.get(i) == B.DList.get(i)) answer = true;
else answer = false;
}
return answer;
}
I have currently written
public boolean isEqualRecursion(A B) {
if DList.size() == 0;
return false();
} else {
}
I know the stopping case is 0 as when size is 0 nothing happens. I have no idea what to write next
Any help will be appreciated
Thanks
I have some code that I would like to make more efficient by recursion.
It is unlikely that you can make it more efficient by recursion. The chances are that it will be less efficient, and also fragile. This is because standard Java compilers don't implement tail-call optimization. The fragility occurs because a recursive comparison algorithm is liable to trigger a stack overflow if the input arrays are large enough.
However, if you want to continue with this as "an exercise", then my HINT is to add an index argument to the isEqualRecursion signature ...
I think that this is a pretty good start for you. This looks through all your elements, assuming they are an array, and then checks if they are equal in size.
public boolean isEqual(ArrayList<?> a, ArrayList<?> b) {
if (a.size() != b.size())
return false;
for (int i = 0; i < a.size(); i++) {
if (!isEqual((ArrayList<?>)a.get(i), (ArrayList<?>)b.get(i))) {
return false;
}
}
return true;
}
Now a couple of things to consider:
This assumes that the content of a(and b) must be an ArrayList at line (ArrayList<?>)a.get(i) what if our ArrayList actually contains something else, like an Integer?
What if our array lists contain null as an item?
What if we pass in two null ArrayLists? (or even just one?)
I'm not sure the point of your function lessThanOrEqualTo(B) is this part of the question or did you write this down wrong?
Also what is a DList?
This is a typical recursion question. You might want to try something like this:
int x = 0;
if(Dlist.get(x) != B.Dlist.get(x)) {
return false;
} else {
x+1;
}
if( x!= dList.size()) {
recursion;
}
return true;
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.
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.