1.计算机随机产生一个【1,100】之间的数字
(1)每次根据玩家的输入与随机数比较后,用户输入数值过大提示玩家too high,用户输入数值过小提示玩家too small,用户猜中提示bingo;
(2)一次游戏终止条件:猜中或超过5次未猜中。猜中输出“You win!”,未猜中输出“You lose!”;
(3)每次游戏终止时,提示用户“是否继续游戏?(Y/N)”,“是”则开始新游戏,“否”则退出游戏;
(4)用户输入0,则输出“用户终止游戏”终止游戏并退出;
(5)设计类中的静态方法(static方法),实现上述功能,方法数量无限制。
public static void main(String[] args) {
int guessNumber = -1;
Tool(guessNumber);
}
@SuppressWarnings("resource")
public static void Tool(int guessNumber) {
while (true) {
if (guessNumber == 0) {
System.out.println("用户终止游戏!");
return;
}
System.out.println("是否开始游戏(Y/N)");
Scanner sc = new Scanner(System.in);
char input = sc.nextLine().charAt(0);
int number = (int) Math.floor(Math.random() * 100);// 生成0-100的随机数
if (input == 'Y') {
System.out.println("开始游戏!");
for (int i = 0; i <= 5;) {
System.out.println("请输入你要猜的数据(1-100):");
Scanner sc2 = new Scanner(System.in);// 接收数据
guessNumber = sc2.nextInt();
if (guessNumber <= 100 & guessNumber >= 0) {
if (guessNumber == 0) {
break;
} else if (guessNumber == number) {
System.out.println("You Win!");
break;
} else {
Guess(guessNumber, i, number);
i++;
}
if (i == 5) {
System.out.println("You lose!");
break;
}
} else {
System.out.println("请输入1-100的数据!");
}
}
} else if (input == 'N') {
System.out.println("退出游戏!");
return;
} else {
System.out.println("请输入正确的符号!");
}
}
}
public static void Guess(int guessNumber, int i, int number) {
// System.out.println(number);
if (number != 0) {
if (guessNumber > number) {
System.out.println("您猜的数字" + guessNumber + "\ntoo hight" + ",您还剩" + (4 - i) + "次机会");
} else if (guessNumber < number) {
System.out.println("您猜的数字" + guessNumber + "\nto small" + ",您还剩" + (4 - i) + "次机会");
}
}
}
2.随机生成有20个元素由组成数组
数组元素使用0-9数字、a-z和A-Z随机生成。
public static void main(String[] args) {
int[] a = new int[20];
int count = 0;
while (count <= 19) {
int t = (int) (Math.random() * 1000);// 抽取的数值小于char类型的“z”
if ((t >= 0 & t <= 9) | (t >= 65 & t <= 90) | (t >= 97 & t <= 122)) {
a[count] = t;
count++;
}
}
for (int i = 0; i < 20; i++) {
if (a[i] >= 0 & a[i] <= 9)
System.out.print(a[i] + "\t");
else
System.out.print((char) a[i] + "\t");
//ASCII
}
}