我花了一段时间,但我想我终于找到了让这个程序工作的方法。我将这些类分成不同的文件,并将权重类重命名为 Record,这样它就更明显了,而不是所有的东西都被命名为权重的某种变化。我还添加了一个 Output 类,以使 main 中的代码尽可能简洁。我希望这与您希望做的类似。
原始代码:“构造函数”
public class WeightIn{
private double weight;
private double height;
public WeightIn (double weightIn, double heightIn){
weight = weightIn; //needs to be : this.weight = weight
height = heightIn; //needs to be : this.height = height
}
项目:weightInApp
包:weightInApp
类:Record.Java
package weightInApp;
class Record
{
private double weight; //declare variables
private double height;
Record (double weight, double height) { //Parameterized Constructor method
this.weight = weight; //this is the correct way
this.height = height;
//if you want to use weightIn and/or heightIn you have to be consistent acrosss
//the whole class. I decided to drop "In" off the variables for brevity.
}
//Getters and setters
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
项目:weightInApp
包:weightInApp
类:Output.Java
该类将设置值输出到控制台上的表格中。这可以手动更改以添加更多数据。您还可以考虑跟踪记录的日期并将其添加到此输出中。您需要在 Record Class 中为该功能添加必要的变量、getter 和 setter。
package weightInApp;
public class Output {
static void output (Record weightIn1, Record weightIn2)
{
int count = 0;
final Object[][] table = new Object[3][3];
table[0] = new Object[] { "Record", "Weight", "Height"};
table[1] = new Object[] { count +=1, weightIn1.getWeight(), weightIn1.getHeight() };
table[2] = new Object[] { count+=1, weightIn2.getWeight(), weightIn2.getHeight() };
for (final Object[] row : table) {
System.out.format("%15s%15s%15s\n", row);
}
}
}
项目:weightInApp
包:weightInApp
类:Main.Java
package weightInApp;
import weightInApp.Record; //imports methods and variables from the other classes
import weightInApp.Output;
public class Main {
public static void main (String [] args){
Record weightIn1 = new Record(0,0);
//previous line of code creates a new Record object named weightIn1
//previous line of code also sets both the values of weight and height to 0.
weightIn1.setWeight(3.65); //sets weight for weightIn1
weightIn1.setHeight(1.70);//sets Height for WeightIn1
Record weightIn2 = new Record(0, 0);
weightIn2.setWeight(3.00);
weightIn2.setHeight(1.75);
//previous 3 lines are the same as above for weightIn1
//except this is for a second object named weightIn2
Output.output(weightIn1, weightIn2); //calls runs passes values to output method
}
}
样本输出
从控制台输出样本