-2

Someone can u help me to show how to make a probability / chance with percentage ?

import java.util.Random;

public class Main {

    public static void main(String[] args) {
        int a = new Random().nextInt(10);
        if (a >= 6) {
            // 60% chance
            System.out.println(a);
            System.out.println("You got a passive power");
        } else if (a >= 3) {
            // 30% chance
            System.out.println(a);
            System.out.println("You got an active power");
        } else if (a >= 1) {
            // 10% chance
            System.out.println(a);
            System.out.println("You got an ultimate power");
        } else {
            // <10% chance (maybe)
            System.out.println(a);
            System.out.println("You blessed with all powers.");
        }
    }
}

Is my program correct ?

Ty

gensart.ai
  • 11
  • 1
  • 5
  • 2
    Your question is so confusing I don't know where to even begin. Your percentages are wrong. What you have for a 60% chance is actually 40% chance. What you have for a 30% chance is actually 30% chance (somehow). What you have for 10% chance is actually 20% chance. What is less than 10% chance in this context? Google "probability formula" and try doing it yourself, and you will see that not only the program is incorrect, but the question is incorrect as well. – Ivan Dimitrov Oct 04 '20 at 10:35

1 Answers1

4

No, your program is not correct.

When you call nextInt(10), you get a number in range 0 to 9, inclusive. You then segment that into the probability ranges you want, without reusing a number:

  0  1  2  3  4  5  6  7  8  9
  └──────────────┘  └─────┘  ╵
    6 / 10 = 60%      30%   10%

Which means the code should be:

int a = new Random().nextInt(10);
if (a < 6) {
    // 60% chance
} else if (a < 9) {
    // 30% chance
} else {
    // 10% chance
}

Or you could go the other way:

//   0  1  2  3  4  5  6  7  8  9
//   ╵  └─────┘  └──────────────┘
//  10%   30%          60%

int a = new Random().nextInt(10);
if (a >= 4) {
    // 60% chance
} else if (a >= 1) {
    // 30% chance
} else {
    // 10% chance
}
Andreas
  • 154,647
  • 11
  • 152
  • 247