Java数字猜测游戏奇怪的输出

时间:2016-02-06 12:14:12

标签: java numbers

Object

我想到了一个数字22,当它问我数字是否为50时输入2.然后它立即转到1.无论我输入什么,它显示1作为输出而不是像50,25, 12等我在Python和C中做了同样的事情,它们运行得很好。

2 个答案:

答案 0 :(得分:4)

high = anslow = ans替换为high = guesslow = guess - 将相应的“猜测范围”边界移动到输入值(1或2),但是至于先前猜测的值,如二元搜索。

答案 1 :(得分:4)

好的,第一个问题是您将ans分配给highlow而不是guess

然后,如果我能给你一些建议:

  1. 每次都不要创建新的扫描仪。相反,请始终使用相同的x扫描仪
  2. 不要在每个if/else块中放置常见操作。相反,将常见操作放在外面。
  3. 你可以给出一次指示(1表示更高等),然后你只要问“你的号码是XX?(0:是,1:更高,2:更低)”。它更具可读性。
  4. 这是一个改进版本,但我相信你可以做得更好:

    public static void main( String[] args ){
        System.out.println( "Welcome to Siddharth's number guessing game. \nThink of a number between 1 and 100 and "
                + "press 1 to continue" );
    
        Scanner x = new Scanner( System.in );
    
        if( x.nextInt() == 1 ){
    
            int high = 100;
            int low = 0;
            int guess = ( high + low ) / 2;
    
            System.out.println( "Is your number " + guess + "? Press 0 if yes, press 1 if your number is higher than " +
                    "this number or press 2 if your number is lower than this number!" );
    
    
            while( true ){
    
                int ans = x.nextInt();
                if( ans == 0 ){
                    break;
    
                }else if( ans == 1 ){
                    low = guess;
    
                }else if( ans == 2 ){
                    high = guess;
    
                }
    
                guess = ( high + low ) / 2;
                System.out.printf( "Is your number %d ? (0: yes, 1: higher, 2:lower) ", guess );
            }
    
            System.out.println( "The number you thought of is " + guess + "! Thanks for playing!" );
    
        }else{
            System.out.println( "No problem. Restart the program and press 1 when ready!" );
        }
    }