I want to decrease the variable loop in for loop. What can I do?
When I do loop--.It will forever loop happened
for (int loop=0;loop<number.length-1;loop++)
{
if (number[loop] != number[loop+1])
{
if (loop > 0 && freq_array[loop-1]== 1 )
{
loop--; //this line
continue;
}
freq=1;
freq_array[loop]=freq;
}
else if (number[loop] == number[loop+1])
{
freq++;
freq_array[loop]=freq;
}
}
#cameron1024 advice me to use while loop but it has forever loop anyway?
while (loop<number.length-1)
{
if (number[loop] != number[loop+1])
{
if (loop > 0 && freq_array[loop-1]== 1 )
{
continue;
}
else
{
freq=1;
freq_array[loop]=freq;
loop++;
}
}
else
{
freq++;
freq_array[loop]=freq;
loop++;
}
}
Firstly, read https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Secondly, a for loop is just a while loop with decoration. For example:
for (<initializer>; <termination>; <increment>) {
<loop body>
}
is identical (with minor scope changes) to:
<initializer>;
while (<termination>) {
<loop body>
<termination>
}
The reason it is looping forever is that you have not changed your termination condition to match the fact that the variable is now decreasing. Your termination condition checks that loop does not go above a certain value. And since loop only ever decreases, that condition is always satisfied, and so the loop continues infinitely.
P.S. avoid naming variables like_this in java, they are typically done likeThis
i think you want this.
for (int loop = number.length - 1; loop > 0; loop--)
If you mean you want to count down:
Just do for(int i=10;i>=0;i--)
int i = 10 makes a new int initialised with 10
The next part is your loops exit condition.
as long a i>=10,the loop will run
And lastly i-- decrement the variable i
Your loop is infinite because the loop++ in the making of the loop and your loop-- are falling together creating a
int i = 1;
while(i < 10) {
i++;
i--;
}
while (loop<number.length-1)
{
if (number[loop] != number[loop+1])
{
freq=1;
freq_array[loop]=freq;
loop++;
}
else
{
freq++;
if (loop > 0 && freq_array[loop-1]== 1 )
{
freq_array[loop-1]=freq;
}
else
{
freq_array[loop]=freq;
}
loop++;
}
}
I'm done now thank you every one.
Related
So I've been stuck trying to get my array list to print out in the right order but it keeps printing the original input i inserted backwards for some reason, i've tried reading the array in reverse order but it doesn't work either.
public static void Add()
{
System.out.println("You may now enter your virtual diary entry...");
System.out.println("You may END the program at any time by typing in endp...\n");
boolean loop = true;
while(loop)
{
String Stop = Cons.nextLine();
if (Stop.equals("endp")| Stop.equals(""))
{
readelements();
break;
} else {
for (int i =0 ; i <= Notes.size(); ) {
Notes.add(i, Stop);
i++;
break;
}
}
}
}
public static void readelements()
{
if (Empty()) {
Empty();
}
for(int i =0; i < Notes.size(); i++) {
System.out.println(i + " = " + Notes.get(i).toString());
Notes.toString();
}
}
In your else block, you break after one iteration (when i = 0) so you're always running Notes.add(0, Stop). This prepends Stop to Notes, so Notes will be in reverse order. Removing the break will cause you to insert duplicate elements into Notes (note that you're looping but always inserting Stop). Try changing your entire else block to just Notes.add(Stop);. This will add the current value of Stop to the end of Notes and should fix your problem.
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 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();
}
}
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
}
I solved a problem recently. But I have this one piece of code where I dont utilize the for loop initialization and condition check. It looks a bit odd that way for a for loop. I want to convert it into a while loop. Please help me do it. I tried many times, but somewhere something is missing.
for(;;current =(current+1)%n){
if(eliminated[current%n]){
continue;
}else{
inkiPinki++;
if(inkiPinki == m){
eliminated[current%n] = true;
printStatus(eliminated, people);
remainingGuys--;
break;
}
}
}
In the above code eliminiated[index] is a boolean.
Edit: Thanks to Geoff who provided me with a solution which I further minimized like this.
while( eliminated[current] || ++inkiPinki != m )
current = (current+1) % n;
eliminated[current] = true;
printStatus( eliminated, people );
remainingGuys--;
All for loops can be converted to while loops using the following pattern:
for (..xxx..; ..yyy..; ..zzz..) {
..aaa..
}
becomes
...xxx...
while (...yyy...) {
..aaa..
..zzz..
}
remember that
for (;;) {
..aaa..
}
is equivalent to
for (nop; true; nop) {
..aaa..
}
where "nop" means no operations.
In your example this makes your loop:
for(;;current =(current+1)%n){
if(eliminated[current%n]){
continue;
}else{
inkiPinki++;
if(inkiPinki == m){
eliminated[current%n] = true;
printStatus(eliminated, people);
remainingGuys--;
break;
}
}
}
equivalent to
// no initialzation needed
while(true) {
//if(eliminated[current%n]){
// continue;
//}else{
if(!eliminated[current%n]){
inkiPinki++;
if(inkiPinki == m){
eliminated[current%n] = true;
printStatus(eliminated, people);
remainingGuys--;
break;
}
}
current =(current+1)%n;
}
From there, you can simplify it further, if you wish.
Try
while( true ) {
if( !eliminated[current] ) {
if( ++inkiPinki == m ) {
break;
}
}
current = (current+1) % n;
}
eliminated[current] = true;
printStatus( eliminated, people );
remainingGuys--;
It should be logically equivalent.
How I would do it:
while (inkiPinki < m) {
if (!eliminated[current % n]) {
inkiPinki++;
if (inkiPinki == m) {
eliminated[current % n] = true;
}
}
if (inkiPinki < m) {
current = (current + 1) % n;
}
}
printStatus(eliminated, people);
remainingGuys--;
This code accomplishes exactly the same thing as your original for loop, except it uses logical tests to determine whether or not it should continue to loop. There's no need for continue or break. If you find yourself using either of these statements, there's probably some refactoring that should be done.
I seem to have an inordinate fondness for using Booleans as integers:
for (;inkiPinki<m; inkPinki += !eliminated[current])
current = (current + 1) %n;
eliminated[current] = true;
printStatus(eliminated, people);
remainingGuys--;
I've also changed current%n to simply current in a couple of places, because the %n is already done where current is incremented, so current should already be reduced modulo n.
If I were doing it, I'd probably change the sense, so instead of eliminated, it was something like remaining:
for (;inkiPinki<m; inkPinki += remaining[current])
current = (current + 1) %n;
remaining[current] = false;
printStatus(remaining, people);
remainingGuys--;