diff --git a/src/src/NGuessNumber.java b/src/src/NGuessNumber.java deleted file mode 100644 index 79bb300773a9220525862539a0a7958d4ab7aa04..0000000000000000000000000000000000000000 --- a/src/src/NGuessNumber.java +++ /dev/null @@ -1,20 +0,0 @@ -import java.util.Scanner; - -public class NGuessNumber { - Scanner scan = new Scanner(System.in); - int [] guesses = new int[4]; - - public void receiveGuesses(){ - for(int i = 0; i < 4; i ++){ - guesses[i] = scan.nextInt(); - } - } - - public static void main(String [] args){ - NGuessNumber game = new NGuessNumber(); - game.receiveGuesses(); - for(int i = 0; i < 4;i++) { - System.out.println(game.guesses[i]); - } - } -} diff --git a/src/src/NewGuessNumber.java b/src/src/NewGuessNumber.java new file mode 100644 index 0000000000000000000000000000000000000000..a3e05f84e1263dd5c8480954f4d0f006826e24cc --- /dev/null +++ b/src/src/NewGuessNumber.java @@ -0,0 +1,93 @@ +import java.util.ArrayList; +import java.util.InputMismatchException; +import java.util.Scanner; +import java.util.Random; + +/** + * @author xiadw + */ +public class NewGuessNumber { + public static Scanner scanner = new Scanner(System.in); + public static ArrayList answers = new ArrayList<>(); + public static ArrayList guesses = new ArrayList<>(); + + private static int NUMBER_AMOUNT = 4; + + private static Random random = new Random(); + public static void main(String[] args) { + 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(!"y".equalsIgnoreCase(again)){ + break; + } + } + } + + public static ArrayList generateAnswer(){ + while(answers.size() < NUMBER_AMOUNT) { + int answer = random.nextInt(10); + if(!answers.contains(answer)){ + answers.add(answer); + } + } + return answers; + } + public static ArrayList 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; + } + 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; + } + public static int getB() { + int b = 0; + for(int i = 0; i < NUMBER_AMOUNT; i++){ + if(answers.contains(guesses.get(i)) && !answers.get(i).equals(guesses.get(i))){ + b = b + 1; + } + } + return b; + } +}