【问题标题】:Why am I getting the error 'cannot find symbol' when I calculate cube numbers?为什么我在计算立方体数时收到错误“找不到符号”?
【发布时间】:2020-06-23 11:31:40
【问题描述】:

我的程序有一个thirdPower 方法,它以number 作为参数并计算从1 到number 的所有数字的三次方(参见Cube Number),即@ 987654328@。该方法将计算出的立方体存储在一个数组中,然后使用 foreach 循环将它们打印出来。

例如调用

thirdPower(15);

应该生成一个包含 1、8、27、...、3375 的数组。

这是我目前的代码,但我收到错误 cannot find symbol:

public class Main {
    public static void main(String[] args){
         thirdPower(15);
}

private static void thirdPower(int number) {
    int[] array = new int[number];
    int count = 1;

    for (int i = 0; i <= getal; i++) {
        array[i] = count * count * count;
        count++;
    }

    for (int numberYe : array) {
        System.out.println(numberYe);
    }
}

我做错了什么?

【问题讨论】:

  • 在您提出下一个问题之前,需要改进的地方很少。 1)您的问题标题 Java simple foreach program 太笼统,根本无法解释您的问题。你的问题标题应该概括问题,并且最好被表述为一个问题。 2)始终将您的编程语言作为第一个标签添加到您的问题中;在这种情况下java。 3)当您遇到错误时,请始终将其(确切的错误消息)包含在您的问题描述中。除此之外,您的描述有助于理解您想要做什么;有一个例子和代码总是很棒!
  • 我还建议您使用tour,阅读help center 中的主题内容,然后阅读How to Ask a Good Question .
  • 这是你的原始代码还是你替换了一些变量名?对我来说,您似乎忘记将 getal 替换为 number
  • @MCEmperor 我同意你的看法——我在审查时也有同样的想法。此外,如果 OP 使用 IntelliJ 之类的 IDE 或稍微研究一下编译器错误消息,这个“问题”将立即显而易见。给 OP 疑问的好处 以及考虑到它周围的其他代码,仅仅用 number 替换 getal 不会 100% 正确——我给出了一个完整的答案......以及关于如何改进这个“问题”和“要求”OP“真诚地”阅读帮助页面的 cmets,OP 将在未来发布“更好”(= 与其他用户的更高相关性)问题。

标签: java arrays loops foreach


【解决方案1】:

第一个 for 循环中的i &lt;= getal 没有定义,所以你会得到编译时错误

Error:(12, 29) java: cannot find symbol
  symbol:   variable getal

要按照您的描述进行操作,您应该将 i &lt;= getal 更改为 i &lt; number,因为您想要

  1. 求从 1 到并包括给定 number 的每个数字的 3 次方,并且
  2. 您以 int i = 0 开始您的 for 循环,这意味着条件必须是 &lt; 而不是 &lt;=,因为您已经将第 0 次计为第一次循环迭代。

这会导致

public class Main {
    public static void main(String[] args) {
        thirdPower(15);
    }

    private static void thirdPower(int number) {
        int[] array = new int[number];
        int count = 1;

        for (int i = 0; i < number; i++) {
            array[i] = count * count * count;
            count++;
        }

        for (int numberYe : array) {
            System.out.println(numberYe);
        }
    }
}

输出为

1
8
27
64
125
216
343
512
729
1000
1331
1728
2197
2744
3375

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-25
    • 2021-09-26
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多