首页 > 解决方案 > 提示用户猜测计算机随机选择的数字的 java 程序

问题描述

我是 Java 的初学者,我试图让这个程序在 1 到 1000 之间选择一个随机数并提示用户猜测这个数字,但程序似乎不起作用,我不知道它有什么问题.

package com.company;

import java.util.Scanner;

public class GradeBookTest {

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);
        guess();
        System.out.println("Guess a number between 1 and 1000.");
        num = input.nextInt();

        if (num >= 1 && num <= 1000)
        {
            while (checkNumber(num) != true)
            {
                System.out.println("Guess again");
                num = input.nextInt();
                checkNumber(num);
            }

            System.out.println("Congratulations. You " +
                            "guessed the number!");
        }
    }

    public static int guess() {
        return ( (int) (1 + Math.random()*1000) );
    }

    public static boolean checkNumber(int a){
      int ans = guess();
      if (a < ans)
      {
          System.out.println("low");
          return false;
      }
      else if (a > ans)
      {
          System.out.println("high");
          return false;
      }
      else
          return true;
    }
}

标签: javaloops

解决方案


尝试这个

public class Guess {
public static void main (String [] args) {
    
    java.util.Scanner input = new java.util.Scanner(System.in);
    
    // Generates the Random Number
    int randomNumber = (int)(Math.random() * 1000);
    
    System.out.print("Guess a number between 1 and 1000: ");
    // Get user guess
    int guess = input.nextInt();
    
    while (guess != randomNumber) {
        // Informs the user whether his guess is high or low
        if (guess > randomNumber) {
            System.out.println("Your guess is high");
        } else {
            System.out.println("Your guess is low");
        }
        // Asks the user for another guess
        System.out.print("Make another guess : ");
        guess = input.nextInt();
    }
    
    System.out.println("Congratulations ! You guessed the number");
}
}

推荐阅读