【问题标题】:counting to 2 different values with main method and public static final int使用 main 方法和 public static final int 计数到 2 个不同的值
【发布时间】:2020-04-23 10:27:42
【问题描述】:

我目前正在解决“练习”问题,但我被困在这个问题上: “假设您正在尝试编写一个使用循环产生以下输出的程序。下面的程序是一个解决方案的尝试,但它至少包含四个主要错误。识别并修复它们。 1 3 5 7 9 11 13 15 17 19 21 1 3 5 7 9 11 "

public class BadNews {
    public static final int MAX_ODD = 21;

    public static void writeOdds() {
        // print each odd number
        for (int count = 1; count <= (MAX_ODD - 2); count++) {
            System.out.print(count + " ");
            count = count + 2;
        }

        // print the last odd number
        System.out.print(count + 2);
    }

    public static void main(String[] args) {
        // write all odds up to 21
        writeOdds();

        // now, write all odds up to 11
        MAX_ODD = 11;
        writeOdds();
    }
}

我已将代码更改为:

public class BadNews {
    public static final int MAX_ODD = 21;

    public static void writeOdds() {
        // print each odd number
        for (int count = 1; count <= (MAX_ODD); count++) {
            System.out.print(count + " ");
            count = count +1; //tried to chacge count++ into count + 2 but it was a miss
        }
    }

    public static void main(String[] args) {
        // write all odds up to 21
        writeOdds();

        // now, write all odds up to 11
        MAX_ODD = 11;
        writeOdds();
    }
}

我认为最后一个问题是最终的 int MAX_ODD 应该移动到 main 并更改为“正常”变量(int MAX_ODD),但它以问题失败结束并注释“您的解决方案必须有一个类常量。一个常量必须是在类中的任何方法之外声明为“public static final”。” 任何想法如何解决这个问题?

【问题讨论】:

  • 我测试了你自己的代码,你只需要从 MAX_ODD 中删除“final”。然后它会按照您的预期运行,并打印您想要的内容。

标签: java loops int final


【解决方案1】:

此代码将为您提供预期的输出。

public static void main(String[] args) {
    writeOdds(21);
    writeOdds(11);
}

public static void writeOdds(int n) {
    // print each odd number
    for (int count = 1; count <= (n); count++) {
        System.out.print(count + " ");
        count = count +1; //tried to chacge count++ into count + 2 but it was a miss
    }
}

【讨论】:

    【解决方案2】:

    声明为 final 的属性在设置初始值后不能更改其值。这个初始值是最终的。变量必须保持在类级别,在任何方法之外,以便每个方法都可以访问它。 所以,干脆删掉final这个词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-19
      • 2016-04-04
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2023-02-22
      • 1970-01-01
      相关资源
      最近更新 更多