lokmir lokmir - 4 days ago 5
Java Question

How to get the nth term of a loop before the loop finishes? in java

I have Loop and I am trying to print the nth term when the loop is less than 40, all of this without stoping the loop when is less than 40. I have tried to print it when the total is less than 40 but I it is pringting the last nth value.

All I need is th nth value when the loop drops bellow 40. I have almost complete my code but this problem is slowing me down.

Working example, This is what the output is supposed to be


Please input mark: 64

Please input number of days to display: 10

Scheme 1

(0) 64 (1) 59 (2) 54 (3) 49 (4) 44 (5) 39 (6) 34 (7) 29 (8) 24

This work can be up to 4 days late before failing.


.

.

This is what my program outputs


Please input mark: 64

Please input number of days to display: 10

Scheme 1

(0) 64 (1) 59 (2) 54 (3) 49 (4) 44 (5) 39 (6) 34 (7) 29 (8) 24

This work can be up to 9 days late before failing.
.


.

loop

// Loop
for(i = 0;i <= numOfDays;i++){
System.out.print("(" + i + ") " + total+ " ");
total = total -5;

if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}

} // End
if (total < 40){
System.out.print("\nThis work can be up to " + i);
}

Answer

I donĀ“t know for sure if I correctly understand what you problem is, but try this code:

int yourValue = -1;

// Loop
for(i = 0;i <= numOfDays;i++){
    System.out.print("(" + i + ") " + total+ "   ");
    total = total -5;
    //yourValue will only be filled the first time total is below 40
    if (total < 40 && yourValue == -1) yourValue = i;
    if (total<=20){
        System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
        break;
    }

}   // End

if (yourValue > -1) System.out.print("\nThis work can be up to " + yourValue + " days late before failing.");

If total falls under 40, the value of i is stored in yourValue

If total falls under 20 the loop is exited and you can continue with the code behind the loop

Comments