初始化破坏了我的代码

时间:2012-12-16 16:00:47

标签: java variables loops for-loop

我是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 个答案:

答案 0 :(得分:0)

如果声明变量并且没有给出默认值(例如):

int row;

如果您尝试在表达式中使用其值:

row = row + 1;

然后编译器抛出错误。找到错误所在的行并分析变量。

更新:在循环中初始化的唯一变量位于for循环中,在第一个语句中(v.g。for(int i = 0; i < 5; i++)初始化i变量)。

答案 1 :(得分:0)

就像这样.........

  • 在java中,当我们在类范围(实例变量)中声明变量时,它会自动分配其默认值。

  • 但是当我们在方法范围(局部变量)声明变量时,必须在使用它之前对其进行初始化。

所以在你的情况下这样做:

int row = 0;

int col = 0;

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

相关问题