简体   繁体   中英

How to count how many times something occures in a loop, java

I am trying to find out how many times the 6 occurs in this loop. I tried array, ArrayList , sapply and others but I still can't make it work.

Here is the code

public class Numbersinhere {
    public static void main(String[] args) {
        int Min = 1;
        int Max = 6;

        for (int y = 0;
             y < 6000;
             y++) {
            int x = Min + (int) (Math.random() * ((Max - Min) + 1));
            System.out.println(x);
            //how many times the 6 ??????????
        }   
    }
}

It throws a dice 6000 times.

I guess I have to use the variable short , but nothing behind that works

Maybe its because of public static void main(String[] args) { but what else should I use in java?

Try this method

public static void main (String[] args) throws java.lang.Exception {
        // your code goes here
        int min = 1;
        int max = 6;
        int reps = 10, x, count = 0;

        for (int y = 0;
             y < reps;
             y++) {
            x = min + (int) (Math.random() * ((max - min) + 1));
            System.out.println(x);
            if(x == 6) {
                count++;
            }
            //how many times the 6 ??????????
        }
        System.out.println("Count = " + count);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM