总循环次数出错

时间:2019-01-07 14:32:07

标签: java loops user-input

以下程序分为两类(两个不同的文件),它们的作用是扫描用户的输入,包括姓名,年龄,身高和体重,并计算每个输入的BMI。 我想在循环的末尾显示循环数,该循环数在Jan7的第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()) + ".");
    }



}

3 个答案:

答案 0 :(得分:1)

您的代码的核心是:

int num = scannerNum.nextInt();
int total = 0;
for (int i = 0; i < num; i++) {
    total += num;
}
System.out.println(total);

这显然是打印num的平方。

您所需的内容似乎已经在person.printData();中完成了。

如果要构建用于打印所有person数据的结构,请使用ArrayList

答案 1 :(得分:1)

Dunno,如果我理解正确,但是如果您想显示当前所在的循环号,请使用循环中的i,如果您不想为零,请使用i + 1。

total = i;

答案 2 :(得分:0)

我可能不了解您真正想要的是什么,但是如果您希望程序显示循环次数,则必须替换

total += num;

使用

total = num+1;