简体   繁体   English

Java 中的赋值运算符无效

[英]Invalid assignment operator in Java

I'm running a super basic program for my class on Java with eclipse, the point of it to write a for loop that prints odd number from 1 to 99 (inclusive) and I'm writing my code我正在使用 Eclipse 为我的 Java 类运行一个超级基本程序,它的目的是编写一个 for 循环,打印从 1 到 99(含)的奇数,我正在编写我的代码

int num1 = 1;
int num2 = 99;
for (num1 => num2 ;; num1 + 2)
    System.out.println(num1);

and it's telling me that + and >= are invalid AssignmentOperators.它告诉我+>=是无效的 AssignmentOperators。 Why is it doing this?为什么要这样做?

You have several problems there.你有几个问题。 The first is you should write <= rather than =>.首先是你应该写<=而不是=>。 The second is you put the loop condition in the wrong place (it should be between the two semicolons).第二个是你把循环条件放在错误的地方(它应该在两个分号之间)。 And lastly you're not assigning new values to num1 (so it never increases).最后,您没有为 num1 分配新值(因此它永远不会增加)。

In addition, you don't need num2 (although it's not a mistake to use it, it makes it a bit less clear).此外,您不需要 num2(虽然使用它不是错误,但它使它不太清楚)。

The final code should look like this:最终代码应如下所示:

int num1 = 1;
for (num1 = 1; num1 <= 99; num1 += 2)
    System.out.println(num1);

Plus, I'm pretty sure you're coding in Java and not JavaScript (they're two different things).另外,我很确定您使用的是 Java 而不是 JavaScript(它们是两种不同的东西)进行编码。

Firstly there is no necessity of defining data type in Javascript.首先,没有必要在 Javascript 中定义数据类型。 That being said you do not need int num1 or num2.话虽如此,您不需要 int num1 或 num2。

This answer is valid if you are using Javascript not JAVA如果您使用的是 Javascript 而不是 JAVA,则此答案有效

Instead can be done this way相反可以这样做

for (i = 1; i < 99 ; i++){
    if(i%2 !== 0){
    console.log(i);
    }else{}

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM