Why isn’t java doing math correctly

I was trying to create a probability calculator for fun, but for some reason, java gets the incorrect answer when I divide two numbers. Here is my code….

import javax.swing.JOptionPane;

public class ProbabilityCalculator {
public static void main(String args[]) {
    String a = JOptionPane.showInputDialog("One out of.....");
    int x = Integer.parseInt(a);
    int numLoops = 1000;
    int y = 0;
    int n = 0;
    for (int i = 0; i < numLoops; i++) {
        int result = (int) (Math.random() * x + 1);
        int result2 = (int) (Math.random() * x + 1);

        if (result == result2)
            y++;
        else
            n++;
    }
    System.out.println(y);
    System.out.println(numLoops);
    System.out.println(y/numLoops);


    double d = (y/numLoops) * 100; //get it? double d??
    JOptionPane.showMessageDialog(null, "Out of " + numLoops + " trials, "
            + y + " times it worked, while " + n + " times it didn't.");
    JOptionPane.showMessageDialog(null, "Your percentage was " + d
            + "%.");
    System.exit(0);
    }
}

When I ran this code one time, y was 514, numLoops was 1000, but d would be 0, when d is supposed to be 51.4 (514 / 1000 * 100). Why is this happening?


Source: java

Leave a Reply