Right now for a Java course I’m trying to build a Mastermind-like game. In this game a 4-digit random number is generated, and the user tries to guess the number. With each guess the computer states how many correct digits are in the right order, and how many correct digits are in the wrong order.
For some reason, everything works up to my binary search for this program, which is really the heart of the program. I’ve spent hours tweaking it and I still cant get it. Any ideas?
In this example I’m trying to guess 9935, I realize that’s not a random number though.
Thanks so much!
EDIT: When I run this program and use the guess “9875”, it does not give me the right results.
The guesses and results I’m required to find are:
Please enter a four-digit number: 9874
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 1
Please enter a four-digit number: 9899
The number of correct digits but in the wrong place: 1
The number of correct digits in the right place: 1
Please enter a four-digit number: 9593
The number of correct digits but in the wrong place: 3
The number of correct digits in the right place: 1
Please enter a four-digit number: 9935
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 4
You are correct!
public class Mastermind {
public static void main(String[] args) {
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int randomNumber = 9935;
int[] randomArray = new int[4];
int temp = randomNumber;
for (int i = 3; i >= 0; i--){
int n = temp%10;
randomArray[i] = n;
temp /= 10;
}
boolean found = false;
while (found == false){
System.out.print(Arrays.toString(randomArray));
int[] guessArray = new int[4];
System.out.print("Please enter a four-digit number: ");
int guessTemp = input.nextInt();
for (int i = 3; i >= 0; i--){
int n = guessTemp%10;
guessArray[i] = n;
guessTemp /= 10;
}
if (Arrays.equals(randomArray, guessArray)){
System.out.println("You are correct!");
found = true;
} else {
int numberRightRight = 0;
int numberRightWrong = 0;
int indexFound = 0;
for(int i = 0; i < guessArray.length; i ++){
System.out.println(randomArray[i]);
indexFound = Arrays.binarySearch(guessArray, randomArray[i]);
System.out.println(indexFound);
if (indexFound >= 0){
if(indexFound == i){
numberRightRight++;
} else {
numberRightWrong++;
}
}
}
System.out.println("The number of correct digits but in the wrong place: " + numberRightWrong);
System.out.println("The number of correct digits in the right place: " + numberRightRight);
}
}
}
If you are not required to use
Arrays.binarySearch(int[], int)you could use your own simple lookup method for an unsorted Array:now instead of calling
Arrays.binarySearch(guessArray, randomArray[i]);just callfindInArray(guessArray, randomArray[i])