【问题标题】:I'm getting an error with <= saying that it's an invalid AssignmentOperator + my code looks wack I think我收到一个错误,<= 说它是无效的 AssignmentOperator + 我认为我的代码看起来很古怪
【发布时间】:2014-08-14 01:21:40
【问题描述】:

所以我陷入了很多这样的困境:

package test;

import javax.swing.*;
import java.util.Random;
import java.util.Scanner;

public class GuessGame {
public static void main(String[] args) 
{
    Scanner keys = new Scanner(System.in);
    System.out.println("Hello! Would you like to play?");
    String choice = keys.next();
    for (choice.equals("y");  choice.equals("yes");)
    {
        System.out.println("Awesome!");
        choice = "";

        Random bill = new Random();
        int j;
        j = bill.nextInt(50);

        System.out.println("Guess what the number I'm thinking is ");
            int number;
            number = keys.nextInt();
                for (number <= (j + 10); number >= (j - 10);)
                    {
                        System.out.println("Warm!");
                        number = 0;
                        number = keys.nextInt();
                    }
                for (number = (j + 5); number == (j - 10);)
                    {
                        System.out.println("Hot!!!");
                        number = 0;
                        number = keys.nextInt();
                    }


    }
    for (choice.equals("n"); choice.equals("no");)
    {
        System.out.println("okay");
        keys.close();
        System.exit(0);
    }
}
}

在带有“ for (number = (j - 10);)”的行上,我在“

谢谢!

【问题讨论】:

  • 当然,绝对没有正确使用那些for() 语句。查看if 语句。
  • &lt;= 不是赋值运算符,而是比较运算符。 for 中的第一个子句必须是赋值语句。

标签: java eclipse assignment-operator


【解决方案1】:

那是因为for statement的第一个参数用于变量的initialization,所以报错。

文档:

for (initialization; termination;increment) {
   statement(s)
}

问题:

for (number <= (j + 10); number >= (j - 10);)

解决方案:

如果您要检查这两个变量,请使用 if statement

  if(number <= (j + 10) &&  number >= (j - 10))

【讨论】:

  • 感谢您向我解释这个概念
【解决方案2】:

尝试用if statements 替换每个for 循环:

if (choice.equals("y") || choice.equals("yes") { 

...

    if (number <= (j + 5) && number >= (j - 5)) { ... } // I assume this is what you meant here
    else if (number <= (j + 10) && number >= (j - 10)) { ... }

...

}
else {
    System.out.println("okay");
    keys.close();
    System.exit(0);
}

请注意,您首先需要最严格的if 语句,因此我更改了您要检查它是否在特定范围内的部分的顺序。这样,它会在检查您是否“热”之前检查您是否“热”(因为热包含在热中)。

另请注意,用于检查“温暖”的else if 语句意味着如果您很热,它不会打扰检查您是否温暖并更新您的输出两次。

我还用else 语句替换了“否”的情况,这将捕获任何不是“y”或“yes”的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多