
用JAVA语言编写一个“猜数字游戏”的程序
要求:CreateaclasscalledGuessingNumberthatincludesAnIntegertypeattributes---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 展开
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 展开
1个回答
展开全部
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
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询