因此,从本质上讲,这是一个简单的循环,该循环应该使物体落下的距离相加10秒钟。当我调试它时,我看到它已传递并且变量具有正确的值,但是当我在我的fallingDistance方法中计算之后立即输入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;
    }
}

最佳答案

请将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;
}

10-08 13:03