[英]Cannot figure out why i'm getting a null value in calculation
So essentially this is a simple loop that should add up for 10 seconds the distance fallen for an object. 因此,从本质上讲,这是一个简单的循环,应该将物体落下的距离相加10秒钟。 When I was debugging it I saw it passed and the variables with correct values but when I entered a println statement right after the calculation in my fallingDistance method, the variable "distance" had a value of zero which I do not see how is possible.
当我调试它时,我看到它已传递并且变量具有正确的值,但是当我在我的fallingDistance方法中计算之后立即输入println语句时,变量“ distance”的值为零,我看不出这是怎么可能的。 What am I missing here?
我在这里想念什么?
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;
}
}
You must assign value to the distance
before using it in main! 在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;
}
Please assign the value returned from fallingDistance(varTime)
method to distance
. 请将
fallingDistance(varTime)
方法返回的值分配给distance
。
Your while loop should be rewritten as: 您的while循环应改写为:
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
distance = fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
Also, your 1/2 will always be evaluated to 0 (because its evaluated as integer). 同样,您的1/2将始终被评估为0(因为其评估为整数)。 The
fallingDistance()
method should be rewritten as: 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.