首页 > 解决方案 > 找不到符号 - 编译错误

问题描述

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

标签: javafor-loopcalculator

解决方案


宣言

你忘了声明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

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

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

还要注意100.0使它成为double.


推荐阅读