1、电脑随机4个不重复数字,顺序也不固定 2、用户从控制台输入一个4位数字,且不能重复 3、用过随机的数字和用户输入的数字计算出XAYB,X和Y是我们要通过程序计算出来的 4、用户有八次机会,结果是4A0B时猜对 用JAVA编写
时间: 2024-09-28 17:08:12 浏览: 44
随机不重复抽签源码下载
在Java中,你可以使用`Random`类生成随机数,并结合`Scanner`类获取用户的输入,然后实现如下的逻辑:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
private static final int NUMBERS = 4; // 4个随机数字
private static final String USER_INPUT = "Enter a 4-digit number with no repeats: ";
private static final int MAX_GUESSES = 8; // 允许的猜测次数
public static void main(String[] args) {
Random random = new Random();
int[] randomNumbers = generateRandomNumbers(NUMBERS);
Scanner scanner = new Scanner(System.in);
int userGuesses = 0;
while (userGuesses < MAX_GUESSES) {
System.out.println(USER_INPUT);
String userInput = scanner.nextLine();
if (!isValidInput(userInput)) {
System.out.println("Invalid input! Please try again.");
continue;
}
int[] userDigits = parseUserInput(userInput);
int result = calculateResult(randomNumbers, userDigits);
if (result == 4000) {
System.out.println("Congratulations! You guessed it right on the " + (userGuesses + 1) + "th try!");
break;
} else {
System.out.println("The code is XAYB, where X and Y are calculated from the random numbers. Try again.");
}
userGuesses++;
}
if (userGuesses == MAX_GUESSES) {
System.out.println("Sorry, you've run out of guesses. The correct code was 4A0B.");
}
}
// 生成随机数组
private static int[] generateRandomNumbers(int size) {
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
numbers[i] = random.nextInt(10); // 生成0到9之间的整数
}
return numbers;
}
// 检查用户输入是否有效
private static boolean isValidInput(String input) {
if (input.length() != 4 || !input.matches("\\d{4}")) {
return false;
}
char[] digits = input.toCharArray();
boolean hasDuplicates = new HashSet<Character>(Arrays.asList(digits)).size() != digits.length;
return !hasDuplicates;
}
// 解析用户输入并返回数字数组
private static int[] parseUserInput(String input) {
return Integer.parseInt(input).toString().chars().mapToObj(c -> c - '0').toArray();
}
// 计算结果,这里只是一个示例,可以根据实际需求调整
private static int calculateResult(int[] randomNumbers, int[] userDigits) {
// 这里可以将两个数组对应位置的元素相乘或做其他运算,例如:
int x = randomNumbers[0] * userDigits[0];
int y = randomNumbers[1] * userDigits[1];
return x * 1000 + y * 100; // 返回xayb的形式
}
}
```
阅读全文