2015-02-10 78 views
1
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 
    } 
} 

/* 我不断收到错误成本显然没有被初始化,但如果它等待输入,它是如何应该做的?*/餐馆账单,初始化错误

+1

在分配任何值之前,您正在计算中使用'cost'。首先为其分配一个值。 – Kon 2015-02-10 21:40:56

回答

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在使用之前需要分配一个值。

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); 
} 
+0

非常感谢。不习惯于在程序的“内部”......有意义的是,它们按照它们写入的顺序运行 – none 2015-02-11 03:32:38

1

你是指的是cost前值都能在这里找到初始化:

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

移动的cost初始化后那些变量的初始化,所以cost时,它的引用将会有一个值。