[英]Trying to call a method with an object, but can't figure out arguments to put
[英]Can't figure out arguments for method
我有一个学校任务,其中我必须创建一个代码,该代码创建并填充一个数组,然后使用这些数据。 我必须计算BMI,确定其BMI是否正常,并且应该将BMI正常的人员的姓名输出到控制台。
卡住的地方是在调用方法输出名称时,我找不到正确的参数。 可能还有其他问题,在这种情况下也请纠正我。
这是我的代码:
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
class TreatedPerson {
String name = "";
int age;
int height;
int weight;
@Override
public String toString() {
return "Name: " + name + " \tAge: " + age + " \tHeight: " + height + " \tWeight: " + weight;
}
}
public class B1 {
static void fillTreatedPerson(ArrayList<TreatedPerson> treatedpeople, int db) {
Random rnd = new Random();
for (int i = 0; i < db; i++) {
TreatedPerson tp = new TreatedPerson();
tp.name = ("Szemely_" + (i + 1));
tp.age = rnd.nextInt(99 - 10 + 1) + 10;
tp.height = rnd.nextInt(200 - 150 + 1) + 150;
tp.weight = rnd.nextInt(150 - 40 + 1) + 40;
treatedpeople.add(tp);
}
}
static void outputTreatedPerson(ArrayList<TreatedPerson> treatedpeople) {
for (TreatedPerson tp : treatedpeople) {
System.out.println(tp);
}
}
static double BMI(TreatedPerson tp) {
return tp.weight / (tp.height * tp.height);
}
static boolean normalBMI(double bmi) {
boolean bmindex = false;
if (bmi > 18.5 && bmi < 24.99) {
return bmindex = true;
}
return bmindex;
}
static void ifnormalBMI(TreatedPerson tp, boolean normalBMI) {
if (normalBMI) {
System.out.println(tp.name);
}
}
public static void main(String[] args) {
ArrayList<TreatedPerson> treatedpeople = new ArrayList<>();
fillTreatedPerson(treatedpeople, 5);
outputTreatedPerson(treatedpeople);
ifnormalBMI();
}
}
由于ifnormalBMI
将一个TreatedPerson
和一个boolean
作为参数,因此您必须在循环中调用它以打印出具有正常BMI的人的姓名。 像这样:
for (TreatedPerson tp : treatedpeople) {
double bmi = BMI(tp);
boolean normal = normalBMI(bmi);
ifnormalBMI(tp, normal);
}
您可以使它成为类似于outputTreatedPerson
的方法,这样您只需要在main
方法的一行中调用它即可。
我在您的代码中看到的另一个问题是这种方法:
static boolean normalBMI(double bmi) {
boolean bmindex = false;
if (bmi > 18.5 && bmi < 24.99) {
return bmindex = true;
}
return bmindex;
}
您将根据条件返回一个boolean
,即boolean
。 您根本不需要在其中执行if语句。 整个方法可以简化为
static boolean normalBMI(double bmi) {
return (bmi > 18.5 && bmi < 24.99);
}
你应该:
for (TreatedPerson person : treatedpeople)
{
double bmi = BMI(person);
boolean isNormalBmi = normalBMI(bmi);
ifnormalBMI(person, isNormalBmi);
}
您的程序中还有另一个错误,那就是BMI总是被计算为零。 这是因为在以下方法中您正在执行整数除法 :
static double BMI(TreatedPerson tp) {
return tp.weight / (tp.height * tp.height);
}
除此之外,BMI是使用以米为单位的高度来计算的。 您似乎已存储了以厘米为单位的高度。 因此,您所有的BMI值都非常小(小于1)。
您应该在循环外部而不是内部实例化对象,为简单起见,请使用getters(如果您不了解getter,则使用Google)将arraylist传递给BMI方法,现在使用for循环计算每个人的bmi。 您并不是只计算一个人的体重指数。 对? 这就是为什么需要for循环的原因。 通过公式计算bmi。 并将其存储在arraylist中。 接下来,将bmi的值传递给checkBMI方法(double bmi)再次创建for循环(int i = 0; I <arraylist.size(); i ++)if(arraylist.get(i).getBMI> 18.5 && if arraylist.get (i).getBMI <24.99)System.out println(arraylist.get(i).getName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.