无法弄清楚为什么我在计算中得到一个空值

时间:2017-06-22 22:06:57

标签: java loops return arguments

所以基本上这是一个简单的循环,应该将对象的距离加起来10秒。当我调试它时,我看到它传递了正确值的变量但是当我在我的fallDistance方法中计算后立即输入println语句时,变量“distance”的值为零,我看不出怎么可能。我在这里缺少什么?

import java.lang.Math;
import javax.swing.JOptionPane;

public class FallingDistance {

    public static void main(String[] args) {
    double distance =0;
        int count = 0;
        double distanceCalc = 0;
        int varTime = 0;
        while (varTime < 10) {
            varTime += 1;
            System.out.println(varTime);
            fallingDistance(varTime);
            distanceCalc += distance;
            JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
        }

    }

    public static double fallingDistance(int varTime) {

        double gravity = 9.8;
        double distance = Math.pow(((1 / 2) * gravity * varTime), 2);
        System.out.println(gravity);
        return distance;
    }
}

2 个答案:

答案 0 :(得分:2)

在main!

中使用之前,您必须为distance指定值
public class FallingDistance {

public static void main(String[] args) {
double distance =0;
    int count = 0;
    double distanceCalc = 0;
    int varTime = 0;
    while (varTime < 10) {
        varTime += 1;
        System.out.println(varTime);
        distance = fallingDistance(varTime);
        distanceCalc += distance;
        JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
    }

}

public static double fallingDistance(int varTime) {

    double gravity = 9.8;
    double distance = Math.pow(((double)(1 / 2) * gravity * varTime), 2);
    System.out.println(gravity);
    return distance;
}

答案 1 :(得分:0)

请将fallingDistance(varTime)方法返回的值指定为distance

你的while循环应改写为:

while (varTime < 10) {
    varTime += 1;
    System.out.println(varTime);
    distance = fallingDistance(varTime);
    distanceCalc += distance;
    JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}

此外,您的1/2将始终被评估为0(因为它被评估为整数)。 fallingDistance()方法应改写为:

public static double fallingDistance(int varTime) {

    double gravity = 9.8;
    double distance = Math.pow((0.5 * gravity * varTime), 2);
    System.out.println(gravity);
    return distance;
}