2012-12-16 40 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;

请原谅我的代码格式化,我在移动中........