M
M
Mikhail Smailovich2019-11-03 12:39:02
Java
Mikhail Smailovich, 2019-11-03 12:39:02

How to set up the counter?

In the proposed code from Eckel, I wanted to calculate the serial number of generating a number, until the moment when it satisfies the condition.
The total number of hits gives out, but I need the counter to increase by 1 after each hit.

package study.it.java.Eccel000077;
 
public class Eccel000077p130loopWhile {
    static boolean condition() {
        double rndm = Math.random();
        System.out.println(rndm);
        boolean result = rndm < 0.99;
        System.out.println(result + ", ");
        return result;
    }
    public static void main(String[] args) {
        int counter = 0;
        while (condition())
            counter++;
        System.out.println(counter);
        System.out.println("Inside 'while'");
 
        System.out.println("Exited 'while");
    }
}

>>>
[...]
0.4126061797246662
true,
0.9893111158958946
true,
0.10166477691349951
true,
0.9965451426395308
false,
13
Inside 'while'
Exited 'while

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-01-20
@Terran37

Your counter is incremented by 1 through ++ and output.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question