Lady Shine
26-04-2017, 18:23
Salve mi è stata "commissionata" la creazione di un "Mastermind" su Java, solo che al posto di colori utilizzo numeri generati randomicamente con math.random. Il problema è che se nell'array generato mi escono due o più numeri uguali allora il mio contatore di numeri giusti al posto sbagliato non va bene. Qualcuno può darmi una mano?
Ecco il codice:
public class MasterMind {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String dividere;
String dividere1;
int contatore = 0;
int contat = 0;
int[] ar = new int[4];
int[] arr = new int[4];
for (int j = 0; j < ar.length; j++) {
System.out.println(ar[j]);
}
for (int k = 0; k < 10; k++) {
System.out.println("Dammi un numero: ");
dividere = sc.nextLine();
for (int i = 0; i < arr.length; i++) {
arr[i] = dividere.charAt(i) - 48;
System.out.println(dividere.charAt(i));
}
for (int i = 0; i < ar.length; i++) {
if (arr[i] == ar[i]) {
contatore = contatore + 1;
}
}
for (int f = 0; f < ar.length; f++) {
for (int j = 0; j < ar.length; j++) {
if (arr[j] == ar[f]) {
contat = contat + 1;
}
}
if (arr[f] == ar[f]) {
contat = contat - 1;
}
}
System.out.println("Hai inserito: " + contat + " numero/i giusto/i al/ai posto/i sbagliato/i.");
System.out.println("Hai inserito: " + contatore + " numero/i giusto/i al/ai posto/i giusto/i.");
if (contatore == 4) {
System.out.println("Complimenti hai vinto!!!");
break;
}
}
}
}
Ecco il codice:
public class MasterMind {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String dividere;
String dividere1;
int contatore = 0;
int contat = 0;
int[] ar = new int[4];
int[] arr = new int[4];
for (int j = 0; j < ar.length; j++) {
System.out.println(ar[j]);
}
for (int k = 0; k < 10; k++) {
System.out.println("Dammi un numero: ");
dividere = sc.nextLine();
for (int i = 0; i < arr.length; i++) {
arr[i] = dividere.charAt(i) - 48;
System.out.println(dividere.charAt(i));
}
for (int i = 0; i < ar.length; i++) {
if (arr[i] == ar[i]) {
contatore = contatore + 1;
}
}
for (int f = 0; f < ar.length; f++) {
for (int j = 0; j < ar.length; j++) {
if (arr[j] == ar[f]) {
contat = contat + 1;
}
}
if (arr[f] == ar[f]) {
contat = contat - 1;
}
}
System.out.println("Hai inserito: " + contat + " numero/i giusto/i al/ai posto/i sbagliato/i.");
System.out.println("Hai inserito: " + contatore + " numero/i giusto/i al/ai posto/i giusto/i.");
if (contatore == 4) {
System.out.println("Complimenti hai vinto!!!");
break;
}
}
}
}