【问题标题】:cannot find symbol - compile errors找不到符号 - 编译错误
【发布时间】:2021-07-21 06:51:46
【问题描述】:

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

【问题讨论】:

  • 阅读错误,它们准确地告诉您缺少什么。对于result,请查看this
  • 您缺少i 的变量声明。此外,result 在 for 循环内声明,因此超出了 for 循环外的 System.out.println() 的范围。
  • 哪一部分没有找到符号i,因为你没有在任何地方声明它是要理解的?
  • int x = ((amount * 10) / 100); - 你会遇到整数除法的问题

标签: java for-loop calculator


【解决方案1】:

所有 cmets 都会给你正确的答案,但要清楚。 首先,如果您在 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);
    }
}

【讨论】:

  • 这个答案只解决了问题的一个方面。请注意,答案应该是完整的,请参阅How to Answer
  • 问题是纠正错误而不是纠正输出。
【解决方案2】:

声明

您忘记声明 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

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多