-4

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?

  • 1
    Duplicate of [*Java Division error*](http://stackoverflow.com/questions/10376322/java-division-error) (within the top four hits on A Well Known Search Engine) and about 150 others. Please search before posting. – T.J. Crowder May 29 '15 at 08:46
  • 1
    @Thomas I can't help hearing "Don't do that" in the voice of Joyce Grenfell as a nursery teacher https://www.youtube.com/watch?v=ZXhHFgDRNBQ (about 40 seconds in). – Jaydee May 29 '15 at 09:20

1 Answers1

1

y/numLoops will be an integer since both arguments are ints. Try (double)y/numLoops or y/(double)numLoops instead.

If you decompose double d = (y/numLoops) * 100; you'll get something similar to those steps:

  • int r = y/numLoops; - according to the spec an operation having two integer operands will have an int result.
  • double d = r * 100 here r will be 0 due to being int.
Thomas
  • 87,414
  • 12
  • 119
  • 157