找不到符号 - 编译错误

时间:2021-07-21 06:51:46

标签: java for-loop calculator

所以目标是根据用户的输入计算 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

2 个答案:

答案 0 :(得分:-1)

声明

您忘记声明 i 变量。

为此,只需在类型前加上前缀即可。

int i = 0
// instead of just
i = 0

范围

另外,你的最终打印

System.out.println(result);

正在尝试使用循环本地的变量 result。所以它不再存在于循环之外。您必须在循环之前创建它:

int result = ...
for (...) {

}
System.out.println(result);

整数除法

最后,这一行不会计算你所期望的:

int x = ((amount * 10) / 100);

这里的问题是你需要整数除法,所以 int / int 也会产生一个 int,所以四舍五入。基本上 1 / 30

您必须使用浮点数,例如 double

double x = ((amount * 10) / 100.0;

另请注意 100.0 使其成为 double

答案 1 :(得分:-1)

所有评论都会为您提供正确答案,但要清楚。 首先,如果您在 for 循环中声明任何内容,它将留在那里。你不能叫它外面的。所以你必须在 for 循环之前做。

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);
    }
}
相关问题