Java中的“猜数字”

时间:2015-04-27 07:59:51

标签: java

我们打算在java中创建一个程序,其中计算机随机猜测1-100之间的数字,并允许用户猜测数字。如果数字低于随机数,程序应该说:更低!更高,程序应该说:更高!如果用户猜到了正确的数字,那么你应该说祝贺你在X次尝试中猜到了正确的数字,这就是我到目前为止所做的,当我在cmd中执行它只是更高或更低的垃圾时我需要帮助解决它。

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

public class GuessingGame{

    public static void main(String[] args) {

        int random, guess, attempts;
        Scanner keyboard = new Scanner(System.in);
        Random generator = new Random();
        random = generator.nextInt(100) + 1;
        attempts = 1; 

        System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");

        guess = keyboard.nextInt(); 
        while (guess != random) {
            if (guess > random) {
                System.out.print("Lower!");
                attempts += 1; 
            }
            else {
                System.out.print("Higher!");
                attempts +=1;
            } 
        }

        System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");

    }        
}

3 个答案:

答案 0 :(得分:2)

你只读取输入一次,然后永远循环它(你读取循环外的输入)。

尝试阅读循环内的输入并使用do-while循环:

guess = 0;        

do {
    guess = keyboard.nextInt(); 

    if (guess > random) {
        System.out.print("Lower!");
        attempts += 1; 
    } else {
        System.out.print("Higher!");
        attempts +=1;
    }
 } while (guess != random);

答案 1 :(得分:1)

guess = keyboard.nextInt();放入while循环中,一次又一次地询问。

答案 2 :(得分:0)

你只需要进行一次猜测并将自己卡在while循环中,就像程序随机化的数字 70 一样,例如,如果用户首次尝试 50 ,代码将输入while loop,因为数字不是 70 ,但它不会出现,因为您编码while(guess != random)并且猜测将等于在我们的情况下是随机的,并且它总是更低无限时间,因为你让他能够进入一次尝试然后你进入一个无休止的循环而不让他有能力改变他的尝试通过它,所以,你必须允许他在while循环中进行他的第二次,第三次,.. iec尝试,如下所示:

    guess = keyboard.nextInt(); 
    while (guess != random) {
        if (guess > random) {
            System.out.print("Lower!");
            attempts += 1; 
        }
        else {
            System.out.print("Higher!");
            attempts +=1;
        }
     guess = keyboard.nextInt();
    }