用JAVA语言编写一个“猜数字游戏”的程序

要求:CreateaclasscalledGuessingNumberthatincludesAnIntegertypeattributes---magi... 要求:Create a class called GuessingNumber that includes
 An Integer type attributes --- magicNum;
 A constructor to initialize the attribute. The attribute should be
initialized to a random integer between 0 and 10. The following class
Random can be used to generate the random integer.
Random random = new Random();
magicNum = random.nextInt(10);
 One method named guess which keeps asking the user to input an
integer between 0 and 10 until the input number is equal to the attribute
magicNum. When the input number is not equal to the attribute
magicNum, the method should output “Please try again, input another
integer between 0 and 10” and wait for the user to input a new integer .
When the input number is equal to the attribute magicNum, the method
should output “Congratulations” and terminate.
Write a test application named TestGuessingNumber to test the program
展开
 我来答
chenhao_89
2017-03-29 · TA获得超过1352个赞
知道小有建树答主
回答量:764
采纳率:83%
帮助的人:441万
展开全部
import java.util.Random;
import java.util.Scanner;

public class GuessingNumber {
    private int magicNum;

    public GuessingNumber() {
        magicNum = new Random().nextInt(10);
    }

    public void guess() {
        Scanner scanner = new Scanner(System.in);
        int expected = Integer.MIN_VALUE;

        System.out.println("Plesae input an integer between 0 and 10: ");
        while(scanner.hasNextInt()) {
            expected = scanner.nextInt();
            if(expected == magicNum) {
                System.out.println("Congratulations");
                break;
            } else {
                System.out.println("Please try again, input another integer between 0 and 10: ");
            }
        }
    }
}
public class TestGuessingNumber {
    public static void main(String[] args) {
        new GuessingNumber().guess();
    }
}

输出结果

Plesae input an integer between 0 and 10:
5
Please try again, input another integer between 0 and 10:
8
Please try again, input another integer between 0 and 10:
1
Please try again, input another integer between 0 and 10:
2
Congratulations

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式