1

我是java编程的初学者。现在我在做一个叫mastermind的游戏。

它有很多条件,我使用数字而不是颜色。

我不知道如何解决这个问题:我正在使用 if else 语句来做我的游戏,但如果解决方案是 4444 并且用户输入是 4444,则输出答案是错误的。

在这个游戏中,第一个输入是计算机生成的,但我必须测试程序,所以我自己设置了数字,第二个输入是玩家输入。

这是我完成的代码:

import javax.swing.JOptionPane;


public class asd {


    public static void main (String args[]){
        int i,j;
        int b=0 ,w=0;

    String input[] = new String[4];
    input[0] = JOptionPane.showInputDialog("input a digit");
    input[1] = JOptionPane.showInputDialog("input a digit");
    input[2] = JOptionPane.showInputDialog("input a digit");
    input[3] = JOptionPane.showInputDialog("input a digit");

     String Uinput[] = new String[4];
     Uinput[0] = JOptionPane.showInputDialog("input a digit");
     Uinput[1] = JOptionPane.showInputDialog("input a digit");
     Uinput[2] = JOptionPane.showInputDialog("input a digit");
     Uinput[3] = JOptionPane.showInputDialog("input a digit");

     for(i=0;i<4;i++){
        for(j=0;j<4;j++){
            if(i<4){
            if(input[i].equals(Uinput[j])){
                if(i==j){
                    b++;
                    i++;
                    j=0;
                }else{
                    w++;


                }
            }
            }
        }
     }
     System.out.println("black = "+b+"\nwhite = "+w);

}
}
4

2 回答 2

4

好的,我会给你一些建议。

首先,我会说要么对每个输入使用单个字符串(如 Dave 建议的那样),要么使用 char 数组。您不需要 4 个字符的字符串数组。

Your "correct" check is way too complicated. You are modifying loop variables in the loop and it makes it hard to decipher what is actually going on.

EDIT

I would modify the algorithm to a two phase one. The first phase, I would walk through the array and ONLY check for the right number in the right spot - this would be your black peg count.

Then, the next phase, I would walk through the arrays again, checking for right number, wrong spot (white count). The tricky thing is handling duplicates. For example, if the actual number is "1234" and I guess "4445", I should only get one white peg. You cannot naively check if the number exists in the actual value.

To address this, the easiest thing I can think of is making a boolean array that keeps track of when you have already accounted for a number. So here's what my "black" phase would look like:

char[] actual = // Read in the real value
char[] guess = // Read in the users guess

int blackCount = 0;
int whiteCount = 0;

boolean[] isFound = new boolean[4];

// Black phase
for (int i = 0; i < 4; ++i)
{
  if (actual[i] == guess[i])
  {
    isFound[i] = true;
    blackCount++;
  }
}

So now you add the white phase - and you only get a white peg if the number exists and it's isFound[i] value = false.

Hope that helps

于 2012-07-04T14:11:32.953 回答
1

I am not sure about mastermind rules and you did not specify, but maybe this is what you mean:

    int b = 0, w = 0;
    for (int i = 0; i < 4; i++)
    {
        if(input[i].equals(Uinput[i])) ++b;
        else ++w;
    }
于 2012-07-04T14:20:08.960 回答