>下面的程序分为两个类(两个不同的文件),它们的作用是扫描用户的输入,包括姓名,年龄,身高和体重,并计算每个输入的BMI。我想在循环结束时显示循环的数量,这在 1 月 7 日的第 28 行中说明,但不知何故显示了用户输入的乘数。代码有什么问题?我该如何解决它?请指教。
import java.util.Scanner;
class Jan7 {
public static void main(String[] args) {
System.out.print("Type a loop number: ");
Scanner scannerNum = new Scanner(System.in);
int num = scannerNum.nextInt();
int total = 0;
for (int i = 0; i < num; i++) {
Scanner scanner = new Scanner(System.in);
System.out.print("Tell us your first name: ");
String scanFN = scanner.next();
System.out.print("Tell us yout last name: ");
String scanLN = scanner.next();
System.out.print("Tell us yout age: ");
int scanAge = scanner.nextInt();
System.out.print("Tell us yout hegiht: ");
double scanH = scanner.nextDouble();
System.out.print("Tell us yout weight: ");
double scanW = scanner.nextDouble();
Jan7Person person = new Jan7Person(scanFN, scanLN, scanAge, scanH, scanW);
person.printData();
total += num;
}
System.out.println(total); //28th line
}
}
class Jan7Person {
public static int count = 0;
public String firstName;
public String lastName;
public int age;
public double height;
public double weight;
Jan7Person(String firstName, String lastName, int age, double height, double weight) {
Jan7Person.count++;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.height = height;
this.weight = weight;
}
public String fullName() {
return this.firstName + " " + this.lastName;
}
public double bmi() {
return this.weight / this.height / this.height;
}
public void printData() {
System.out.println("Your name is " + this.fullName() + ".");
System.out.println("Your age is " + this.age + ".");
System.out.println("Your BMI is " + Math.round(this.bmi()) + ".");
}
}
代码的核心是:
int num = scannerNum.nextInt();
int total = 0;
for (int i = 0; i < num; i++) {
total += num;
}
System.out.println(total);
这显然打印了num
的正方形.
您需要的似乎已经在person.printData();
中完成了.
如果要构造一个用于打印所有person
数据的结构,请使用Array
或List
。
如果我理解正确,Dunno,但如果你想显示你所在的当前循环号,只需使用循环的 i,或者 i+1,以防万一你不想有一个零。
total = i;
我可能不明白你真正想要的是什么,但如果你想让程序打印循环的轮数,你必须替换
total += num;
跟
total = num+1;