计算餐馆账单的总提示和税金

时间:2016-04-24 05:19:30

标签: java

我需要使用两种方法。一个是getMealCharge(),需要返回mealCharge而不需要参数。第二个是computeAndPrintTotalBill(),需要在该方法中进行计算。

我的问题是 - 当我从第一种方法获得用户输入时,如何将该数字应用于第二种方法以便计算。

如果我把所有内容放在第一个方法上,它就会起作用。但是,由于某些原因,在第二种方法中它不会出现。如果有人能帮我找到我做错了什么。谢谢。

import java.util.Scanner;
public class ComputeTip{ 

   final double taxRate = 0.0725;
   final double tipRate = 0.15; 
   double mealCharge;
   double tax;
   double tip;
   double total;

   public double getMealCharge(){

      System.out.println("Enter meal charge: ");
      Scanner keyboard = new Scanner(System.in); 
      mealCharge = keyboard.nextDouble(); 
      return mealCharge;
   }

   public void computeAndPrintTotalBill(double getMealCharge, double mealCharge){

      Scanner keyboard = new Scanner(System.in);
      tax = mealCharge * taxRate;
      tip = mealCharge * tipRate;
      total = mealCharge + tax + tip;

      Test.println("charge: " + mealCharge);
      Test.println("tax: " + tax);
      Test.println("tip: " + tip);
      Test.println("total: " + total);   
   }
}

2 个答案:

答案 0 :(得分:1)

您只能使用computeAndPrintTotalBill方法通过修改方法和变量来完成工作:

final static double taxRate = 0.0725;
final static double tipRate = 0.15;

public static void computeAndPrintTotalBill(double mealCharge) {

double tax= mealCharge * taxRate;
double tip = mealCharge * tipRate;
double total= mealCharge + tax + tip;

    System.out.println("charge: " + mealCharge);
    System.out.println("tax: " + tax);
    System.out.println("tip: " + tip);
    System.out.println("total: " + total);
}
public static void main(String...args){

Scanner keyboard = new Scanner(System.in);
Double mealCharge = keyboard.nextDouble(); 
computeAndPrintTotalBill(mealCharge);

}

输出:

21.5
charge: 21.5
tax: 1.5587499999999999
tip: 3.225
total: 26.28375

注意:您也可以

 ComputeTip computeTip = new ComputeTip();
 double mealCharge = computeTip.getMealCharge();
 computeTip.computeAndPrintTotalBill(mealCharge);

在原始程序中(需要从方法签名中删除double getMealCharge)。这也很好。

答案 1 :(得分:1)

您使用的参数错误。 试试这个:

public void computeAndPrintTotalBill(){
    double mealCharge = getMealCharge();
    tax = mealCharge * taxRate;
    tip = mealCharge * tipRate;
    total = mealCharge + tax + tip;
    Test.println("charge: " + mealCharge);
    Test.println("tax: " + tax);
    Test.println("tip: " + tip);
    Test.println("total: " + total);
 }