我正在尝试使用(宾果游戏),(靶心游戏)编写Java代码,规则很简单:
电脑选择 4 个数字
用户输入 4 个数字
必须检查用户输入是否在 1 到 10 之间
如果用户输入存在于计算机随机数字中,它将是 1 个公牛
如果一个数字存在于计算机随机数字的同一位置,它将显示 1 个“眼睛”
最大限制为 20 次尝试,直到用户被视为“失败”;我需要通过用户输入打印每一轮有多少公牛和多少只眼睛;
例子:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
我的代码最后打印 0 和 0 。
谢谢您的帮助!
这是我的代码:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}