【问题标题】:Why does my variable don't "remember" the changes in the if-Statement?为什么我的变量不“记住” if 语句中的更改?
【发布时间】:2020-03-13 00:10:58
【问题描述】:

我的代码有问题:我的程序将绘制几个特定的​​矩形。因此,我使用循环来重复计算新矩形的大小。

    int c = readInt("Counter: ");
    double width1 = readDouble("Width: ");
    for (int i = 0; i <= c; i++) {

        double height1;
        double lastwidth;
        double lastheight;
        double topleftx;
        double toplefty;


        if ((i == 1) && (i != 0)) {
            topleftx = 0;
            toplefty = 0;
            height1 = width1 / 1.618;
            GRect rect = new GRect(topleftx, toplefty, width1, height1);
            add(rect);
            lastwidth = width1;
            lastheight = height1;
        }
        ;

        if ((i == 2) || ((i - 2) % 4 == 0) && (i != 0)) {
            height1 = lastheight;
            width1 = height1 / 1.618;
            toplefty = toplefty;
            topleftx = topleftx + lastwidth - width1;
            GRect rect = new GRect(topleftx, toplefty, width1, height1);
            add(rect);
            lastwidth = width1;
            lastheight = height1;
        }
    }

但是我收到了一些类似的错误消息: 局部变量 lastheight 可能尚未初始化。 在行中:第二个循环的height1 = lastheight;。 但是我已经在第一个循环中初始化了我的变量。所以这就像我的变量忘记了我在第一个循环中给它的值......?!

但是为什么呢?我该如何解决这个问题?

感谢您的帮助。 :)

【问题讨论】:

    标签: loops if-statement variables


    【解决方案1】:

    在声明时用默认值初始化 height1 变量。

    因为编译器会检查每种情况,例如如果第一个 if 语句从未运行会发生什么情况,在这种情况下,height1 变量将未初始化...

    因此,在这些类型的情况下,始终使用一些默认值或虚拟值初始化变量。例如。

    double height1 = 0.0;
    

    【讨论】:

    • 永远欢迎,请投票回答以帮助...! :)
    【解决方案2】:

    先尝试给它们默认值:

    double height1 = 0.0;
    double lastwidth= 0.0;
    double lastheight=0.0;
    double topleftx=0.0;
    double toplefty=0.0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      相关资源
      最近更新 更多