英文:
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 <= 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);
}
}
}
答案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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论