boolean已分配但从未访问过

时间:2015-06-22 19:59:44

标签: java while-loop boolean

我只是想创建一个GuessMyNumber游戏,这是我的代码:

import java.util.Random;
import java.util.Scanner;

public class classic {
public static void main(String[] args) {
    Random rand = new Random();
    boolean beaten = false;
    int number;
    int randn = rand.nextInt(99);
    //System.out.println(randn);
    System.out.println("What is my number? Guess it!");
    Scanner input = new Scanner(System.in);
    int counter = 0;
    int counter2 = 0;
     while(beaten = true){
            number = input.nextInt();
            if (number == randn) {
                System.out.println("Correct!");
                beaten = true;
            }
            if (number < randn) {
                System.out.println(number + " is too low");
            }
            if (number > randn) {
                System.out.println(number + " is too high");
            }
        }
    }
}

在while循环中,我设置beaten = true但仍然循环

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

while(beaten = true)

由于=是一个赋值运算符,因此首先将true分配到beaten,然后while loop条件变为,

beaten = true
while(true) {
//.... hence, loop executed.
}

使用比较运算符==进行条件检查。此外, not !操作也可用于boolean变量。

说,

beaten = true

然后

while(!beaten) 

装置

while(!true) // read while not true
//implies
while(false) {
//.... loop will not going to execute.
}

答案 1 :(得分:0)

import java.util.Random;
import java.util.Scanner;

public class Guess {
public static void main(String[] args) {
    Random rand = new Random();
    boolean beaten = false;
    int number;
    int randn = rand.nextInt(99);
    //System.out.println(randn);
    System.out.println("What is my number? Guess it!");
    Scanner input = new Scanner(System.in);
    int counter = 0;
    int counter2 = 0;
     while(beaten == false ){
            number = input.nextInt();
            if (number == randn) {
                System.out.println("Correct!");
                beaten = true;
            }
            if (number < randn) {
                System.out.println(number + " is too low");
                counter++;
            }
            if (number > randn) {
                System.out.println(number + " is too high");
                counter++;
            }
        }
     System.out.print("It took you " + counter + " tries to gues the number");
    }
}

现在它有效。你设置&#34; beaten&#34;最初是假的,所以它没有工作,我也改变了你的while循环条件&#34; beaten == false&#34;而不是&#34; beaten = false&#34;希望这可以帮助。我不知道你想对这个计数器做什么,所以我把它添加到底部以计算它花了多少次尝试。