gpt4 book ai didi

java - 无法从 for 循环中获取总和

转载 作者:行者123 更新时间:2023-12-01 06:32:52 25 4
gpt4 key购买 nike

这是我的代码:

public void checkOut() {   
double sum;
System.out.println("Checking out items ...");
for (int i = 0; i < purchases.length; i++) {
sum =+ purchases[i].getPrice();
System.out.println(purchases[i].getDescription() + "/" + purchases[i].getPrice());
}
System.out.println("Amount due: " + "$" + new DecimalFormat("0.00").format(sum));
}

当我编译它时,我收到此错误:

The local variable sum may not have been initialized.

或者,当我将总和行更改为double sum = sum +purchasing[i].getPrice();

我收到以下错误:

sum cannot be resolved to a variable.


它基本上是一种获取购物篮中元素列表的方法;打印商品及其单独价格,然后查找商品的总价(总和)。

谁能告诉我我做错了什么?

最佳答案

只需初始化您的变量:

double sum = 0.0;

在 Java 中,本地方法变量必须在使用之前进行初始化。在本例中,您刚刚声明了 sum 变量,但尚未初始化。

请注意,该错误非常具有描述性:局部变量 sum 可能尚未初始化。(强调我的)。

Alternatively when I change the sum line to > double sum = sum + purchases[i].getPrice(); I get Error: sum cannot be resolved to a variable. (emphasis and syntax/grammar fixes mine).

这是因为您的 sum 变量现在位于 for 循环的范围内,而您在外部使用它,这是错误的。编译器告诉您 sum 变量之前从未声明过,因此无法使用它。

这就是问题所在(仅限模板):

for(...) {
double sum = ...
}
//the compiler will complain asking what is this sum variable?
System.out.println(sum);

other answer 中所述,您的添加代码有错误。解决所有这些问题后,您的代码将如下所示:

public void checkOut(){   
double sum = 0.0;
System.out.println("Checking out items ...");
for (int i = 0; i<purchases.length; i++) {
sum += purchases[i].getPrice();
System.out.println(purchases[i].getDescription() + "/" +
purchases[i].getPrice());
}
System.out.println("Amount due: " + "$" +new DecimalFormat("0.00").format(sum));
}

关于java - 无法从 for 循环中获取总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16534764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com