java 如何打印乘客最多的公司名称?[已关闭]

ia2d9nvy  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(118)

3天前关闭。
Improve this question
我需要这个java程序的帮助。任务是写一个程序,接收n个航班公司,然后直到命令"完成"接收每个公司的乘客。在程序结束时,结果应该是每个公司的名称和该公司的平均乘客人数。还有,必须打印乘客最多的公司的名称。我想出了如何打印每个公司的名称和每个航班的平均乘客人数,但最后,我不知道如何打印乘客最多的公司名称。在我的情况下,乘客最多的公司名称是最后一个整数,而不是公司名称。
这是密码:

Scanner scanner = new Scanner(System.in);

int n = Integer.parseInt(scanner.nextLine());
String companyName = "";
int sum = 0;
int counter = 0;
String topCompany = "";
int mostPeople = 0;

for (int i = 0; i < n; i++) {
    int maxNumber = 0;

    String input = scanner.nextLine();
    companyName = input;
    char symbol = companyName.charAt(0);
    boolean isSymbol = false;

            if (symbol>=65 && symbol<=90){
                isSymbol = true;
            }

            if (isSymbol){
                topCompany = companyName;
            }

    while (!input.equals("Finish")) {

        if (sum > maxNumber) {
            maxNumber = sum / counter;
            mostPeople = maxNumber;


        }

        input = scanner.nextLine();

        if (input.equals("Finish")) {
            break;
        }
        int people = Integer.parseInt(input);
        counter++;
        sum += people;
    }

    System.out.println(companyName);
    System.out.println(sum / counter);
    counter = 0;
    sum = 0;

}
System.out.printf("%s has most passengers per flight: %d", topCompany, mostPeople);
mlmc2os5

mlmc2os51#

我发现你总是把变量topCompany赋给最新的公司,我想你可以在开始的时候用一个max变量来解决这个问题,比如int topCompanyByNrOfPasagers=0
然后比较每个公司的sum,就在while循环之后:

if (sum > topCompanyByNrOfPasagers) {
  topCompany = companyName;
}

另外,我建议您更详细地命名变量,例如:maxNumber-〉更像是maxAveragePerCompanymostPeople-〉mostAverageOfPeople,我花了一点时间才弄明白它们是什么。
另外,如果你在循环开始的时候重置你的计数器,我能推荐它更容易遵循程序吗?

for(...) {
counter = 0;
sum = 0;

主方法编码应为:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int n = Integer.parseInt(scanner.nextLine());
    String companyName = "";
    int sum = 0;
    int counter = 0;
    String topCompany = "";
    int mostPeople = 0;
    int topCompanyByNrOfPasagers = 0;
    int maxNumber = 0;

    for (int i = 0; i < n; i++) {

      String input = scanner.nextLine();
      companyName = input;

      while (!input.equals("Finish")) {
        if (sum > maxNumber) {
          maxNumber = sum / counter;
          mostPeople = maxNumber;
        }
        input = scanner.nextLine();

        if (input.equals("Finish")) {
          break;
        }
        int people = Integer.parseInt(input);
        counter++;
        sum += people;
      }

      if (sum > topCompanyByNrOfPasagers) {
        topCompany = companyName;
        topCompanyByNrOfPasagers = sum;
      }

      System.out.println(companyName);
      System.out.println(sum / counter);
      counter = 0;
      sum = 0;

    }
    System.out.printf("%s has most passengers per flight: %d", topCompany, mostPeople);
  }

相关问题