餐厅账单,初始化错误

restaurant bill, initializing error

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
   }
}  

/* 我不断收到成本显然尚未初始化的错误,但如果它正在等待输入,它应该怎么做?*/

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

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

将那些变量的初始化移到cost的初始化之后,这样cost在被引用时就会有值。

看看你是如何声明变量的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);
}