餐馆账单,初始化错误

时间:2015-02-10 21:39:56

标签: java java.util.scanner

import java.util.Scanner;
import javax.swing.JOptionPane;

public class RestaurantBill3
{
   public static void main(String [] args)
   {
      //Constant
      final double TAX_RATE = 0.0675;      
      final double TIP_PERCENT = 0.15;

      //Variables                             
      double cost;  
      double taxAmount = TAX_RATE * cost;              //Tax amount 
      double totalWTax = taxAmount + cost;             //Total with tax
      double tipAmount = TIP_PERCENT * totalWTax;            //Tip amount
      double totalCost = taxAmount + tipAmount + totalWTax;  //Total cost of meal

      Scanner keyboard = new Scanner(System.in);

      System.out.print("What is the cost of your meal? ");
      cost = keyboard.nextDouble();

      System.out.println("Your meal cost $" +cost);

      System.out.println("Your Tax is $" + taxAmount);

      System.out.println("Your Tip is $" + tipAmount);

      System.out.println("The total cost of your meal is $" + totalCost);

      System.exit(0);                                        //End program
   }
}  

/ * 我一直收到成本显然没有被初始化的错误,但是如果它在等待输入,它应该怎么做呢?* /

2 个答案:

答案 0 :(得分:1)

您指的是cost在此处初始化之前的值:

double taxAmount = TAX_RATE * cost; 
double totalWTax = taxAmount + cost;       

cost初始化后移动这些变量的初始化,因此cost在引用时会有一个值。

答案 1 :(得分:0)

看看如何声明变量cost。您正在声明一个变量,但您没有为其赋值,因此它未初始化。我认为有一个更大的概念问题。我们来看看你的代码:

double cost;  // this is uninitialized because it has not been assigned a value yet
double taxAmount = TAX_RATE * cost;              //Tax amount 
double totalWTax = taxAmount + cost;             //Total with tax
double tipAmount = TIP_PERCENT * totalWTax;            //Tip amount
double totalCost = taxAmount + tipAmount + totalWTax;  //Total cost of meal

在这里,发生的事情是你声明变量并将它们的值设置为表达式的结果 - 等号的右侧。在这种情况下,程序流是自上而下的,并且这些语句是顺序执行的。当taxAmount和您的其他变量被声明和分配时,cost的值是未知的。这会导致编译器错误。尝试重写这样的代码,请记住在使用之前需要为cost分配一个值。

public static void main(String [] args) {
    //Constant
    final double TAX_RATE = 0.0675;      
    final double TIP_PERCENT = 0.15;

    //Variables                             
    double cost, taxAmount;  // rest of variables

    Scanner keyboard = new Scanner(System.in);

    System.out.print("What is the cost of your meal? ");
    cost = keyboard.nextDouble();

    System.out.println("Your meal cost $" +cost);

    taxAmount = TAX_RATE * cost;
    System.out.println("Your Tax is $" + taxAmount);

    // rest of code

    System.exit(0);
}