简体   繁体   English

无法退出do while循环,即使表达式为false

[英]Can't exit the do while loop ,even the expression is false

import java.util.*;
public class number_guassing_game{
    private static int a = 0;
    public static void main(String[] args) {
       Scanner in=new Scanner(System.in);
       int number=(int)(Math.random()*100+1);
       int count=0;
       boolean flag = true;
       do {
           int a = in.nextInt();
           count+=1;
           if(a>number) {
               System.out.println("smaller!");
           }else if(a<number) {
               System.out.println("bigger!");
           }
        }while(a != number); 
        System.out.println("congratulations!"+" You have guessed "+count+" times!");
    }
}

在此输入图像描述

Obviously the answer is 48, but it didn't the loop and print the expression. 显然答案是48,但它没有循环并打印表达式。

The loops condition 循环条件

while(a != number);

doesn't see the local variable into which you read the input: 没有看到您读取输入的局部变量:

int a = in.nextInt();

It sees the static variable initialized to 0 that never changes: 它看到静态变量初始化为0 ,永远不会改变:

private static int a = 0;

Therefore the loop never terminates. 因此循环永远不会终止。

You should change 你应该改变

int a = in.nextInt();

to

a = in.nextInt();

Oh, and there's no reason for a to be static . 哦,而且也没有理由astatic It could be a local variable of the main method, as long as it is declared outside (and before) the loop. 它可以是main方法的局部变量,只要它在循环外部(和之前)声明。

The a you define inside the loop shadows the a from outside it. a你在循环中定义的阴影a从外面。 That a is never updated, and thus the loop will only be terminated if you enter 0 (the original value a was initialized with). a永远不会更新,因此只有输入0 (原始值a初始化为)时才会终止循环。 In order to avoid this, just use the same a instead of declaring a new variable: 为了避免这种情况,只需使用相同的a而不是声明一个新变量:

a = in.nextInt(); // no datatype here, since you aren't defining a new variable

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

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