I am writing a mastermind game, here are my codes:
import java.util.*;
public class mm {
public static void main(String[] args) {
System.out.println("I'm thinking of a 4 digit code.");
int[] random=numberGenerator();
int exact=0, close=0;
while(exact!=4){
int[] guess=userinput();
exact=0;
close=0;
for(int i=0;i<guess.length;i++){
if(guess[i]==random[i]){
exact++;
}
else if(random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]){
close++;
}
}
if(exact==4){
System.out.println("YOU GOT IT!");
}
else{
System.out.println("Exact: "+exact+" Close: "+close);
}
}
}
public static int[] userinput(){
System.out.println("Your guess: ");
Scanner user = new Scanner(System.in);
String input = user.nextLine();
int[] guess = new int[4];
for (int i = 0; i < 4; i++) {
guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
}
return guess;
}
public static int[] numberGenerator() {
Random rnd = new Random();
int[] randArray = {10,10,10,10};
for(int i=0;i<randArray.length;i++){
int temp = rnd.nextInt(9);
while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
temp=rnd.nextInt(9);
}
randArray[i]=temp;
}
return randArray;
}
}
Now the program works. However, I want to add a function that if user's input is"*", the program prints "cheat code entered. The secret code is: XXXX(//the random number that generated)" then continue asking. I've tried to wrote a separate cheat()
function in order to achieve this. But it calls thenumbergenerator()
again so the secret code change everytime. How to avoid this problem? Or are there any other way to achieve this function?
BTW, here is the logic of the cheat function:
if (guess.equals("*")){
System.out.format("cheat code entered. The secret code is:")
for(int i=0;i<guess.length;i++){
System.out.print(guess[i]);
}
}