首页 > 解决方案 > 理解 for 循环的困难

问题描述

我不明白我该怎么办?问题是

从用户那里读取城市数量(至少 6 个城市)

对于每个城市:输入城市名称和人数(最少 10 人)。

对于城市中的每个人:应输入体重和身高,必须计算和打印 BMI 和 BMI 类别。

对于每个城市,应计算并打印每个 BMI 类别中的人数和百分比。

最后,程序应打印一份包含以下详细信息的摘要报告:

我试图做的:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int NumberOfCity;
        System.out.printf("Enter number of Cities:  (Minimum of 6 cities required) ");
        NumberOfCity = input.nextInt();
        if (NumberOfCity < 6){
            System.out.print("Enter A number more than 6");
        } else {
            System.out.printf("Number of cities are " + NumberOfCity);
        }
        while (NumberOfCity >0){
            String city; int NumberOfPerson;
            System.out.printf("Enter The Name of the city");
            city = input.next();
            System.out.printf("Enter The number of persons for the city  (Minimum of 10 Persons Required)");
            NumberOfPerson = input.nextInt();
            if (NumberOfPerson < 10){
                System.out.printf("Enter A Number more than 10");
            } else {
                while (NumberOfPerson > 0){
                    int mass , height ;
                    System.out.printf("Enter The mass of the person");
                    mass = input.nextInt();
                    System.out.printf("Enter The Height of the person");
                    height = input.nextInt();
                    double BMI = mass / Math.pow(height,2);
                    if (BMI < 18.5){
                        System.out.printf("The person BMI is UnderWeight");
                        int x = 0;
                        x +=1;
                    } if (BMI ==18.5 && BMI <25){
                        System.out.printf("The person BMI is Normal");
                        int y = 0;
                        y +=1;
                    } if (BMI ==25 && BMI <30){
                        System.out.printf("The person BMI is Overweight");
                        int z = 0;
                        z +=1;

                    } else {
                        System.out.printf("The person BMI is Obese");
                        int a =0;
                                a+=1;
                    }
                }
            }
            NumberOfCity--;
        }
    }
}

标签: javafor-loopwhile-loopjava.util.scanner

解决方案


不考虑一些明显的问题(如评论中所述),您不应该尝试一次全部完成。

  • 把问题分解成小步骤。首先读取值并打印它们以确保其有效。
  • 对于其他部分,暂时注释掉现在应该可以工作的控制台输入部分,并根据需要将固定输入分配给字段和数组。这将使您的任务更轻松,速度更快。当程序的其他方面已经过测试和工作时,您可以恢复到控制台输入。
  • 然后再次从控制台获取输入,对其进行最终测试。做任何最后的清理和记录。

如果您遇到无法正常工作的问题,这就是 SO 的用途。如果您在理解部分作业时遇到问题,您应该与您的导师讨论。


推荐阅读