Я просмотрел вашу программу и пересмотрел ее, оставив свои отзывы в комментариях в тех местах, где они актуальны. Я надеюсь, что этот обзор поможет!
import java.util.*;
public class FlipaCoin {
public static void main(String[] args) {
Random rand = new Random();
// don't
// - boolean a;
// If you're going to test a variable,
// assign it a default value first
boolean a = true;
// Declaring these outside of the `while` loop below allows
// them to exist through multiple executions of the loop's body
int heads = 0;
int count = 0;
double percentage = 0;
// It turns out that `percentage == 50.0` never evaluated to `true`, ever
// Better to pick a limit beyond which
int samples = 5000;
// don't - while (a=true) {
// Using the `=` operator assigns a value to a variable,
// and this assignment itself results in a true, and loop forever
// Using the `==` operator compares two operands for equality
// of values, and returns true if same, false if different
// This is how to test `a`.
// while (a == true) {
// We don't want it to loop forever though, so the condition was revised
// `<=` is a "less than or equal to" comparison operator
while (count <= samples) {
int flip = rand.nextInt(2);
// don't do this inside the loop
// - int heads = 0;
if (flip == 1) {
heads++;
}
// don't do these inside the loop
// - double count = 0;
// - double percentage = heads / count;
// Assigning a new value to a variable defined
// outside the loop is what you want;
// `(double) count` says "think of this value as a double" in just this line
// but `count` stays int, so when logging below, it doesn't show as `105.00`
percentage = heads / (double) count;
// don't - System.out.println(percentage);
// Give a little more context for what you're logging! :)
System.out.println("Sample: " + count + "; Percent: " + percentage);
count++;
// don't, this will never succeed
// - if (percentage == 50.0) {
// - break;
// - }
}
}
}