首页 > 解决方案 > 使用Java中的方法计算数组中各种索引的不同双精度值

问题描述

我正在创建一个程序,该程序接收成分及其每盎司的卡路里,然后是食谱及其成分和每种成分的盎司数。我想计算食谱的总卡路里。

import java.util.*;

public class Restaurant {

    

        for (int i=0; i<numRecipes; i++) { 
            System.out.println(recipeName[i] + ":"); 
            System.out.println(" calories"); // I would call the countCalories method here
        }
    }

}

标签: javaarraysmethods

解决方案


对代码的几点说明:

  1. 每次您询问收据的成分时,您都会在 for 循环内构建一个新的成分使用,但您不会将其保留为类级别,因此在每次 for 循环迭代后它都会被销毁(它的范围在 for 循环内)。如果最后你只想知道每个食谱的卡路里总数,你应该在 numIngredients 循环之后计算这些卡路里,但仍然在 numRecipes 循环内,所以你仍然有你的成分使用列表

  2. 要计算一个食谱的卡路里总数,您需要计算每种成分的卡路里。卡路里[0] 中的值对应于成分名称[0],但这不一定与成分使用[0] 相同。因此,对于每个成分使用元素,您首先需要在成分名称中查找成分以了解其索引号,然后您可以使用该索引号查找该成分的卡路里。

  3. 如果您真的想知道所有食谱及其使用的成分,您需要构建一个二维数组,其中维度一是每个食谱,维度 2 是成分用于食谱。

    String[] recipeName = new String[numRecipes];
    // extra array to keep calories per recipe
    double[] recipeCalories = new double[];
    
    for (int i=0; i<numRecipes; i++) {
        recipeName[i] = scan.next(); 
        int numIngredients = scan.nextInt();
        String[] ingredientsUsed = new String[numIngredients];
        double[] numOunces = new double[];
    
        for (int j=0; j<numIngredients; j++) { 
            ingredientsUsed[j] = scan.next();
            numOunces[j] = scan.nextDouble();
        }
        recipeCalories [i]=countCalories(ingredientsUsed,ingredientName,calories,numOunces);
    }
    
    for (int i=0; i<numRecipes; i++) { 
        System.out.println(recipeName[i] + ": calories "+recipeCalories[i]); 
    }
    
    /**
     * ingrediensUsed : names of all ingredients in the recipe
     * ingredientName: names of all known ingredients
     * calories: calories per ingredientName
     * numOunces : ounces per ingredientUsed
     */
    int countCalories (String[] ingredientsUsed, String[] ingredientName, double[] calories, double[] numOunces) {
      int cal=0;
      for (int i=0;i<ingredientsUsed.length;i++) {
          for (int n=0;n<ingredientName.length;n++) {
              if (ingredientsUsed[i].equals(ingredientName[n]) {
                  // n is the corresponding index in the ingredientName and calories arrays
                 cal = cal+ ((int)(numOunces[i] * calories[n] + 0.5));
              }
          }
      }
      return cal;
    }
    

推荐阅读