2012-12-16 41 views
-2

我是新來的java,我目前正在研究這個學期的最後一個項目(CS Major),我遇到了「變量可能未被初始化」的錯誤。我已經嘗試過網站上的其他修補程序,但每當我做它時,都會使用初始化的變量而不是我在循環中定義的變量。初始化遺址我的代碼

public static void main(String[] args) { 
    double priceperpound  = 2; // price per pound of coffee 
    int numberofbags   = 2; // number of pounds of coffee 
    double bagweightinpounds = 1; // weight of the bag in punds 
// double pricebeforetaxes = 8; // total before taxes 
// double totalpricewithtaxes = 0; // total price 
    double taxrate    = .065; // whats the tax? 
    double TotalWeight   = 0; // total weight of purchase 
// double discountprice  = 0; // discounted price 
// double discount   = .9; // if you qualify the price before taxes will be  multiplied by this 
    int row; 
    int col; 

    PriceCalculator calculations = new PriceCalculator(priceperpound, numberofbags, 
      bagweightinpounds, taxrate); 

    for (bagweightinpounds = 1; bagweightinpounds <= 5; bagweightinpounds = bagweightinpounds + 1) { 

     for (numberofbags = 2; numberofbags <= 1024; numberofbags = numberofbags * 2) 
     { 
      System.out.printf("%f", calculations.getBasePrice()); 
     } 
    } 
    Scanner input = new Scanner(System.in); 
} 
+2

Java不是C或Pascal。只在需要時才聲明變量,並在同一時間初始化變量,而不是在方法的開始處全部聲明它們。儘量創建儘可能簡短的方法。 –

+0

這是你的完整代碼嗎?因爲它最終錯過了a}。 – fonZ

+0

你可以把斷點,看看你到底在哪裏得到錯誤。不知道Java編譯器是否保證編譯一個'double',它沒有被聲明爲0.0,0.0d或0.0D ......只是一個想法。 – bonCodigo

回答

0

如果要聲明一個變量,並給它沒有默認值(例如):

int row; 

,如果你嘗試使用其值的表達式:

row = row + 1; 

然後編譯器會引發錯誤。找到錯誤所在的行並分析變量。

更新:循環中初始化的唯一變量在for循環中,在第一個語句中(例如for(int i = 0; i < 5; i++)初始化變量i)。

+2

它不會拋出異常。實際上它將無法編譯。 –

+0

但是不是在循環開始時初始化的值?循環是我能找到的代碼的唯一地方 – user1908047

+0

@RohitJain你是對的。更正... – SJuan76

0

及其這樣.........

  • 在java中,當我們聲明在類範圍(例如變量),其自動分配它的默認值的變量。

  • 但是,當我們在方法範圍(局部變量)聲明一個變量時,它必須在使用之前初始化。

你的情況

所以像這樣做:

INT行= 0;

int col = 0;

請原諒我的代碼格式化,我在移動中........