因此,目标是根据用户的输入计算3个月后累积的利息金额(10%(。然而,我犯了太多错误。为什么?
import java.util.Scanner;
public class showCase {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int amount = scanner.nextInt();
for(i=0; i<3; i++) {
int x = ((amount * 10) / 100);
int result = amount - x;
amount = result;
}
System.out.println(result);
}
}
./Playground/showCase.java:7: error: cannot find symbol
for(i=0; i< 3; i++) {
^
symbol: variable i
location: class showCase
./Playground/showCase.java:7: error: cannot find symbol
for(i=0; i< 3; i++) {
^
symbol: variable i
location: class showCase
./Playground/showCase.java:7: error: cannot find symbol
for(i=0; i< 3; i++) {
^
symbol: variable i
location: class showCase
./Playground/showCase.java:12: error: cannot find symbol
System.out.println(result);
^
symbol: variable result
location: class showCase
4 errors
所有注释都给出了正确的答案,但要明确。首先,如果您为循环声明内部的任何内容,它将保持不变。你不能在外面叫它。所以你必须在循环之前做这件事。
import java.util.Scanner;
public class showCase {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int amount = scanner.nextInt();
int result = 0;
for(int i=0; i<3; i++) {
int x = ((amount * 10) / 100);
result = amount - x;
amount = result;
}
System.out.println(result);
}
}
声明
您忘记声明i
变量。
为此,只需在其前面加上类型即可。
int i = 0
// instead of just
i = 0
范围
此外,您的最终打印
System.out.println(result);
正在尝试使用循环本地的变量CCD_ 2。因此,它不再存在于循环之外。你必须在循环之前创建它:
int result = ...
for (...) {
}
System.out.println(result);
int除法
最后,这条线不会计算出你所期望的:
int x = ((amount * 10) / 100);
这里的问题是,你需要整数除法,所以int / int
也会产生int
,所以向下取整。基本上1 / 3
就是0
。
您必须使用浮点数字,例如double
。
double x = ((amount * 10) / 100.0;
还要注意使其成为double
的100.0
。