1 Star 0 Fork 7

宋煜/xlcx01

forked from 筱泷澄汐/xlcx01 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
NewGuessNumber.java 2.99 KB
一键复制 编辑 原始数据 按行查看 历史
邢龙 提交于 2024-03-27 10:02 . On branch xinglong
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class NewGuessNumber {
public static Scanner scanner = new Scanner(System.in);
public static ArrayList<Integer> answers = new ArrayList<>();
public static ArrayList<Integer> guesses = new ArrayList<>();
private static int NUMBER_AMOUNT = 4;
private static Random random = new Random();
public static void main(String[] args) {
scanner = new Scanner(System.in);
System.out.println("欢迎来到新猜数字游戏!");
while (true) {
answers = generateAnswer();
while (true) {
System.out.println("请输⼊4个0-9之间不重复的整数:");
guesses.clear();
guesses = receiveGuesses();
int a = getA();
int b = getB();
System.out.println(a + "A" + b + "B");
if (a == 4 && b == 0) {
System.out.println("恭喜你!猜对啦!");
break;
}
}
System.out.println("再玩⼉⼀次吗?(y/n)");
String again = scanner.next();
if (!again.equalsIgnoreCase("y")) {
break;
}
}
}
/**
* @author xinglong
*/
public static ArrayList<Integer> generateAnswer() {
while (answers.size() < NUMBER_AMOUNT) {
int answer = random.nextInt(10);
if (!answers.contains(answer)) {
answers.add(answer);
}
}
return answers;
}
/**
* @author xinglong
*/
public static ArrayList<Integer> receiveGuesses() {
while (guesses.size() < NUMBER_AMOUNT) {
int guess;
try {
guess = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("请输⼊数字!");
scanner.next();
continue;
}
if (guess < 0 || guess > 9) {
System.out.println("请输⼊0-9之间的整数!");
continue;
}
if (!guesses.contains(guess)) {
guesses.add(guess);
} else {
System.out.println("数字已经存在!");
}
}
return guesses;
}
/**
* @author xinglong
*/
public static int getA() {
int a = 0;
for (int i = 0; i < NUMBER_AMOUNT; i++) {
if (answers.get(i).equals(guesses.get(i))) {
a = a + 1;
}
}
return a;
}
/**
* @author xinglong
*/
public static int getB() {
int b = 0;
for (int i = 0; i < NUMBER_AMOUNT; i++) {
if (answers.contains(guesses.get(i)) && answers.get(i) !=
guesses.get(i)) {
b = b + 1;
}
}
return b;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/song_yua/xlcx01.git
git@gitee.com:song_yua/xlcx01.git
song_yua
xlcx01
xlcx01
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385