【发布时间】:2012-12-06 07:22:23
【问题描述】:
我正在为我正在为课程作业制作的饮食编程制作 BMI 计算器。最初我制作了几个变量 public static 来从另一个类中获取变量。我的 BMI 计算器以这种方式运行良好。
然后我发现我可以使用 get 方法(获得更多分数)。所以我将前面的变量改为private,并使用了get 方法。但是当我运行这个程序时,当程序打印出保存 BMI 的变量时,我得到 NaN,这以前从未发生过!
谁能帮忙?
import java.util.Scanner;
public class Weight {
private Scanner input;
private String readInput;
private String userWeightIsPounds;
private String userWeightIsStones;
private Scanner input2;
public static double userWeight;
public Weight(){
userWeightIsPounds = ("Pounds");
userWeightIsStones = ("Stones");
}
public void findOutUserWeightMessage(){
System.out.println("Firstly Do you weigh yourself in pounds or stones?");
}
public void findOutUserWeight(){
input = new Scanner (System.in);
readInput = input.nextLine();
if(readInput.equals(userWeightIsPounds)){
System.out.println("Ok then, enter your weight in pounds please.");
}
if(readInput.equals(userWeightIsStones)){
System.out.println("Ok enter your weight in stones please.");
}
input2 = new Scanner (System.in);
userWeight = input2.nextFloat();
if (userWeight > 20){
System.out.println("You've enetered your weight as " + userWeight + " lbs. I'll save that information for later.");
}else{
userWeight = userWeight * 14;
System.out.println("I've converted your weight into pounds for you. You weigh " + userWeight + " lbs. I'll save that information for later.");
}
}
public double static getUserWeight(){
return userWeight;
}
}
还有进行计算的类的代码。忽略一些我试图找出我的变量发生了什么的println。
public class BMI {
private double userHeightSqaured;
private double bmiMutiplier;
private double weightDivideHeight;
private double userBmi;
private double userWeightBmi;
private double userHeightBmi;
BMI(){
bmiMutiplier = 703;
userWeightBmi = Weight.getUserWeight();
userHeightBmi = Height.getUserHeight();
}
public void startUpBmiMessage(){
System.out.print("Lets start with your BMI then shall we? ");
}
public void calculateUserBmi(){
System.out.println("userWeightBmi is " + userWeightBmi);
System.out.println("userWeightBmi is " + userHeightSqaured);
userHeightSqaured = userHeightBmi * userHeightBmi;
System.out.println("userHeightSqaured is " + userHeightSqaured);
weightDivideHeight = userWeightBmi/userHeightSqaured;
System.out.println("weightDivideHeight is " + weightDivideHeight);
userBmi = weightDivideHeight * bmiMutiplier;
System.out.println("weightDivideHeight is " + weightDivideHeight);
System.out.println("bmiMutiplier is " + bmiMutiplier);
}
public void calculateUserBmiMessage(){
System.out.println("Your bmi is " + userBmi);
}
}
【问题讨论】:
-
只是一个提示 - 关键字
static不应出现在代码中的任何位置(当然,main方法除外) -
感谢删除静态。但是eclipse一直告诉我要把修饰符改成static!
-
@JonathanCanning - 你明白
static是什么意思吗?static变量是什么?static方法是什么?为什么不能从静态方法访问实例变量?回到你的讲义/教科书/任何东西,阅读这些主题。