Java循环内需要变量。

huangapple go评论74阅读模式
英文:

Java Variable expected inside a for loop

问题

public class Main {
    public static void main(String[] args) {
        int remainder = 0;
        int remainders[] = new int[20];
        int j = 1;
        int remaindersMax = 0;
        while (true) {
            for (int i = 1; i <= 20; i++) {
                j % i = remainders[i];  // 这一行有错误,需要修正
                for (int k = 0; k < remainders.length; k++) {
                    if (remaindersMax < remainders[i]) {
                        remaindersMax = remainders[i];
                    }
                }
            }
            if (remaindersMax == 0) {
                break;
            }
            System.out.println(j);
        }
    }
}
英文:

I'm pretty new here and new to Java in general. I'm trying to solve a projecteuler question and I thought I had a solution but got stick with this error that I cannot fix. Just to give you an idea of what I was going for(in case it wasn't clear) this is the question:
"What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
I don't want a solution but rather any help with getting rid of the "Java Variable expected inside a for loop." error would be appreciated.

public class Main {
    public static void main(String[] args) {
        int remainder = 0;
        int remainders[] = new int[20];
        int j = 1;
        int remaindersMax = 0;
        while (true) {
            for (int i = 1; i &lt;= 20; i++) {
                j % i = remainders[i];
                for (int k = 0; k &lt; remainders.length; k++) {
                    if (remaindersMax &lt; remainders[i]) {
                        remaindersMax = remainders[i];
                    }
                }
            }
            if (remaindersMax == 0) {
                break;
            }
            System.out.println(j);
        }
    }
}

答案1

得分: 0

j % i = remainders[i];

是无效的语法。变量赋值的左侧(LHS)只能包含一个变量,而不是表达式。右侧(RHS)可以包含任意复杂的表达式。您想要将数组remainders中的索引i的值赋予取模操作的结果。交换左侧和右侧,使您的程序可以编译:

remainders[i] = j % i;
英文:
j % i = remainders[i];

is invalid syntax. The left hand side (LHS) of a variable assignment can only contain a variable, not an expression. The right hand side (RHS) can contain arbitrarily complex expressions. You want to assign the array remainders at index i the value of the modulo operation. Swap LHS and RHS to make your program compile:

remainders[i] = j % i;

huangapple
  • 本文由 发表于 2020年10月24日 01:01:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64504349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定