I wrote a piece of code which should be executed until the condition is satisfied. I have 2 classes using the same structure. In one of them while (true) loop executes as expected; in the other class the program exits the loop after the first recursion.
protected static boolean flag = true;
private static int value=0;
private static int limit=10;
.
.
.
public static int method(){
if (limit-value <=0)
{
...
}
else {
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
}
}
return int_Value;
}
I expect the while(true) loop to be executed until the condition is satisfied (which is more than once).
With some cleaned up indentation it becomes clear that the while loop contains an unconditional return.
if you look at your code the while loop goes like this
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
after executing either if or if else statement there is a return int_value statement which is causing the problem
Although I did debugging I couldn't see it in the first place. I performed another debug session after #user3437460 's suggestion, so I was able to find out:
It seems like an additional return statement was used!(return int_Value;),
the one after else if block. So, the program returns a value and never goes back into the loop.
After deleting the first return statement, program runs just fine.
Related
I want only the while loop to start over if the if condition inside is true.
In my book this is achieved with breaking the loop, to let it start over.
Problem with this code is: The break does nothing but stopping the while loop. If the if condition is true, nothing gets repeated. The method returns the value of x and it is over.
How can I get the while loop repeat if the if condition is met, in this example?
Thank you :)
public int example() {
for() {
if() {
//code
}else{
z=0;
while (z==0) {
//code
if() {
//code
break;
}else{
z=1;
}
}
}
}
return x;
}
Here break; keyword is breaking the whole while loop if condition is true. And as the code has nothing else to execute after while loop has ended, the code returns 'X'.
I suppose that is not what you want.
You can either use continue keyword instead of break.
Or you can consider refactoring a method out of:
//code
if() {
//code
break;
}else{
z=1;
}
like below:
public boolean condtionalRepeat(){
//code
if() {
//code
return true;
}else{
return false;
}
}
and the code will look like:
public int example() {
for() {
if() {
//code
}else{
//code
while (condtionalRepeat()) {
//code
}
}
}
return x;
}
An additional comment on the original code: if this is accurate:
while (z==0) {
//code
if() {
//code
break;
}else{
z=1;
}
}
then it collapses to
//code
if() {
//code
}else{
z=1;
}
The loop never loops. The first time through (in the original code) either the 'if' condition is satisfied, or it is not satisfied.
If satisfied, we end with a 'break' out the loop.
If not satisfied, we set z to 1, then loop to evaluate the 'while' condition, which terminates the loop.
Either way the loop executes once only.
So I'm trying to find whether array a is a subset of array b, and my code is as follows :`
public class subset {
public static boolean subset(int[]a, int[] b) {
for(int i=0;i<a.length;i++){
for(int j=0;i<a.length;j++){
if(a[i]==b[j]){
return true;
break;
}else{
return false;
}
}
}
}
public static void main(String[]args){
int[] a = {1,2,6};
int[] b = {1,2,4,3,7,4,8,5};
if (subset(a,b))
System.out.println("Array 1 is contained in Array 2");
else
System.out.println("Array 1 is not contained in Array 2");
}
}
And I am getting the following errors: unreachable statement and missing return statement.
What I want to do is that when the if condition is true it stops the inner for loop and carries on with the outer for loop.
Thanks in advance
2 things need to be fixed. You need to remove break, and add a return false at the end.
public static boolean subset(int[]a, int[] b) {
for(int i=0;i<a.length;i++){
for(int j=0;i<a.length;j++){
if(a[i]==b[j]){
return true;
//break; remove this
}else{
return false;
}
}
}
return false; //add this
}
Also, you could simplify it a bit, by doing this, instead of the if..else
return a[i]==b[j];
First problem is this:
return true;
break;}
the second line will never be executed because the first one terminates the method execution. Decide which line you want here: return a value or jump out of the inner loop (neither I presume, this branch should be empty, see below).
The second problem is that when you pass in an empty array the loops are not executed and the method does not have a value to return. Here simply add a "return true" (or false, quite arbitrary here) at the end of the method.
You probably can simplify the loop body in this way:
if(a[i]!=b[j]){
return false;
}
is it possible by any means in the following method that the print statement get executed after the if statement returns true in the for loop?
public boolean contains(Object o) {
if(o == null){
throw new IllegalArgumentException();
}
for(int i = 0; i < size(); i++){
if(o.equals(getNodeAt(i).data)){
System.out.println("contains passed here: "+o+" "+getNodeAt(i)+" "+i);
return true;
}
System.out.println(getNodeAt(1));
}
System.out.println("cointain failed here "+o);
return false;
}
Of course; call the method again. More effectively, efficiently, and specifically with an Object such that o.equals(getNodeAt(i).data is false. The truth is...
"[B]y any means" is a pretty loose constraint; you say...
is it possible by any means in the following method that the print statement get[s] executed after the if statement returns true in the for loop?
I'm saying that YES, that's possible by any means when the means are recalling the method. In fact, it's perpetually true as long as you're using whatever container.
Proof:
Assume that it is impossible by any means in the following method that the second return statement gets executed after the if statement returns true in the for loop.
static String proof(Object o) {
for(int i = 0; i < 1; ++i) {
if (o == null) {
return "I'm returning from the for loop!!!";
}
}
return "I'm now called after the for's return statement (by any means)!! - QED";
}
But given...
public static void main(String...args) {
System.out.println(proof(null));
System.out.println(proof(new String("Hello Proof!")));
}// end main method
the ouput is...
I'm returning from the for loop!!!
I'm now called after the for's return statement!! - QED
Therefore our assumption is wrong and it is possible by some means for the second return statement to get executed after the if statement returns true in the for loop.
;)
A "better" way to phrase that so it's clear what you're asking would be, perhaps, - "Is it possible for the code in a method body to continue to execute after a return statement?"
That answer is no and can be tested in any good IDE as follows.
static String proof(Object o) {
for(;;)
if(true)
return "Donkey Butts";
return "Poops";
}
This basically says forever it is true that I will return "Donkey Butts". In any IDE I'd waste my time using you will get an error for "unreachable statement". The IDE can determine this truth from your code which implicitly is telling you that any time the loop is active and the if is true the code below cannot execute.
No, it is definitely not possible.
No, but it is possible that System.out isn't flushed until after the return statement.
Yes, if you enclose in a try and finally.
public boolean contains(Object o) {
if(o == null){
throw new IllegalArgumentException();
}
for(int i = 0; i < size(); i++){
try {
if(o.equals(getNodeAt(i).data)){
System.out.println("contains passed here: "+o+" "+getNodeAt(i)+" "+i);
return true;
}
} finally {
System.out.println(getNodeAt(1));
}
}
System.out.println("cointain failed here "+o);
return false;
}
Nothing inside a method can be executed after the return statement.
But when you deal with output operations, things can happen quite differently from what you might expect. In fact, writes to an output file/device are often buffered, i.e. written to an internal array. When the array is full, it is sent to the file/device. This happens for efficiency reasons, because writing a few big chunks of data is faster than writing lots of small ones.
This means that these operations sometimes seem to happen long after the place where they appear in the code.
This is how I would do a while loop:
boolean more = true;
while (more)
{
// do something
if (someTest())
{
more = false;
}
}
That's pretty standard. I'm curious to know if there's a way of doing something similar to the code below in Java: (I think I've seen something like it in C)
// The code below doesn't compile (obviously)
while (boolean more = true)
{
// do something
if (someTest())
{
more = false;
}
}
I only ask this because currently I don't like the way I'm defining the variable used in the condition (in this case: "more") outside the scope of the loop, even though it's only relevant inside the loop. There's no point it being left hanging around after the loop has finished.
* * Update * *
An idea came to me following a visit to the Porcaline Chamber of Secrets:
for (boolean more=true; more; more=someTest())
{
// do something
}
It's not perfect; It's abusing the for loop and I can't think of a way to execute the loop at least once, but it's close... Is there a way to make sure the loop is performed 1+ times?
To answer your question literally, you can do
for(boolean more = true; more; ) {
more = !someTest();
}
but this is much the same as
while(!someTest());
If it must execute at least once you can do
do {
} while(!someTest());
For your specific case, you can reduce your code to this:
while (true) {
if (someTest()) {
break;
}
}
In general, you could replace your outer-scope declaration with an inner-scope one, but you'd need to move the loop condition:
while (true) {
boolean more=true;
...
if (someTest()) {
more = false;
}
...
if (!more) {
break;
}
}
Or even:
do {
boolean more=true;
...
if (someTest()) {
more = false;
}
...
if (!more) {
break;
}
} while (true);
I'd opine that defining your condition outside the loop is clearer.
KidTempo, in the example you gave, I think that more would be re-initialized each time through the loop. Each time through the loop, the conditional is re-evaluated, so assuming that you are able to define a variable in a conditional, the variable would be re-initialized each time that conditional is re-evaluated. This would also apply to other types of conditionals, so I would say to avoid defining variables in a conditional.
I was wondering what will be returned in a java program when you have multiple returns in a program.
private int numberReturner()
{
if (a) return a;
else if (b) return b;
for (int i = 1; i < board.size()-1; i++)
{
if (c) return c;
}
return d;
}
So lets say a is true, (it should return a), but wouldn't it return d because that is the final line of code in the whole program? Why is this so?
Sorry if I worded this a bit strangely...
Once any 'return' statement is encountered the method will exit execution and return that value.
That method will return d only if no other return statement is encountered before reaching that last line.
Normally, the first "return" encountered will be the one returned. But if there is a "return" statement encountered in a finally block, the "return" in the finally block will be returned.
e.g.
private int m1(){
try{
return 1;
}finally{
return 2; //this will be returned instead
}
}
If you've already "returned" you are never going to hit the subsequent returns.
The method returns a because the return statement exits from the current method, and control flow returns to where the method was invoked. Please read more about different branching keywords in Java tutorial. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Once a return statement is executed the method ends and if it is not void the return value is returned.
I know only one exception to this rule, and you have it with the finally statement.
Take this example:
public static void main(String[] args) {
System.out.println(test());
}
private static int test() {
try {
return 1;
} finally {
return 2;
}
}
in this case test() returns 2, because the finally statement in this case is always executed before exit the method.
The current execution thread will leave a method the first time it encounters a return statement (the notable exception to this rule is with try...finally blocks, where, once a return is encountered, the finally{...} block executes before leaving the method.