Caitlin Caitlin - 4 months ago 29
Java Question

Division not returning the correct value

This code is part of a code that will eventually be much longer, so ignore parts of it that aren't relevant yet. Right now, I'm having a problem with the value of p. I am trying to make p=(X0)/(2*N). I am inputting 16 for X0, 20 for T, and 20 for N, so the value should equal 0.4. However, I keep getting 0.0. What am I doing wrong here?

import java.util.*;
public class WrightFisherModel {
public static void main(String[] args) {

System.out.println("Enter X0 value");
Scanner x = new Scanner(;
int X0 = x.nextInt();

System.out.println("Enter T value");
Scanner t = new Scanner(;
int T = t.nextInt();

System.out.println("Enter N value");
Scanner n = new Scanner(;
int N = n.nextInt();

double p = (X0 / (2 * N));



What's happening is you're storing all your values as int which means it's trying to use integer division instead of floating point division, and obviously integers can't store decimals. Try changing the types of X0, T and N to double, or casting them to double before dividing.

Additionally, you're reading them using nextInt which means if you enter 1.5 into the console it won't read it properly, so change those to nextDouble.