Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

How do I use modulus for selection of 4 statements iterated through a loop of 100 in Java?

I am trying to use a loop in conjunction with the modulus operator. I need to use the modulus operator as a selection tool, to select one of 4 statements. These 4 statements have to be selected one at a time until the loop has executed 20 times. This means that each of the 4 statements has been executed 5 times.

I do not understand how the modulus operator can specifically select one of these statements one after another through the loop of 20 iterations. How does the loop know when to execute any of the statements at the correct time. So we have the four statements 1,2,3, and 4. Then this is repeated until the loop of 20 iterations has been cycled through.

I understand that the modulus operator returns the remainder of a division. And a for loop can be used to iterated over some code. It is just the combination of these things that I am struggling with.

Also I understand that a switch statement could be used also.

Can anybody please explain how to use the modulus operator to select one of four statements repeatedly over a loop of 20 so that each statement has been executed 5 times in this sequence?

do 1 thing (one loop iteration) do 2 thing (2nd loop iteration) do 3 thing 3rd loop iteration) do four thing (4th loop iteration)

This sequence must be repeated in order, returning to (1thing) and repeated until 20 iterations has been completed.

The use of modulus is required.

question from:https://stackoverflow.com/questions/65839332/how-do-i-use-modulus-for-selection-of-4-statements-iterated-through-a-loop-of-10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Normally for homework I don't give code, but in this case it's simpler and cleaner to use code, and you are earnestly needing a boost:

for (int i = 0; i < 100; i++) {
    switch (i % 4) { // values will be in the range 0 to 3 inclusive
        case 0:
            // do something 1
            break;
        case 1:
            // do something 2
            break;
        case 2:
            // do something 3
            break;
        default:
            // do something 4
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...