我正在写一个策划游戏,这是我的代码:
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;
}
}
现在程序正常运行。但是,我想添加一个功能,如果用户的输入是&#34; *&#34;,程序会输出&#34;输入的作弊码。密码是:XXXX(//生成的随机数)&#34;然后继续问。我试图写一个单独的cheat()
函数来实现这一目标。但它再次调用numbergenerator()
,因此秘密代码每次都会改变。如何避免这个问题?或者还有其他方法来实现这个功能吗?
BTW,这是作弊函数的逻辑:
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]);
}
}
答案 0 :(得分:1)
作弊就是这样:
if (guess.equals("*")){
System.out.format("cheat code entered. The secret code is:")
for(int i=0;i<random.length;i++){
System.out.print(random[i]);
}
}
编辑:从userinput()
A)随机传递给userinput()
作为参数
public static int[] userinput(int[] random){
...
B)随机成为一个成员变量(可能是更好的方法)
public class mm {
static int[] random;
public static void main(String[] args) {
System.out.println("I'm thinking of a 4 digit code.");
random=numberGenerator();
...