I’m a beginner in java programming. Now I’m doing a game called mastermind.
It has many conditions and I’m using numbers instead of colours.
I have no idea of how to solve this problem: I’m using if else statement to do my game but if the solution is 4444 and user input is 4444, the output answer is wrong.
In this game the first input is computer generated, but i have to test the program, so i set the number by myself, and the second input is the player input.
Here is the code i’ve done:
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);
}
}
Ok, i’m going to give you some suggestions.
First I would say either use a single String for each input (as Dave suggested) or use a char array. You don’t need an array of String’s for 4 characters.
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:
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