So I'm doing homework, and it is supposed to be a game of cows and bulls.
I have generated 4 random integers to be guessed, and the user enters a 4 digit number. I then validate that the number is indeed 4 digits long and turn it into a array of CHARs. After that, I wanted to compare the randomly generated numbers one by one with the elements in the array, and if they are equal, add a "1" to a counter.
I have tried many solutions that I found on the internet to similar problems, some very difficult ones I have not as they seemed like overkill, because I am still very new to programming and I feel as though I am missing something simple and obvious. The problem is, everytime I iterate through the array, the elements should match, but the condition is always "False".
Here is the problematic part of the code:
Scanner Sc1 = new Scanner(System.in);
if(Sc1.hasNextInt()){ // is it a number ? ?
int user_guess = Sc1.nextInt();
String user_guess_string = Integer.toString(user_guess); // how.
int length = user_guess_string.length(); // many
if(length != 4){ //digits
System.out.println("On vaja 4 numbrid.Mäng hakkab otsast pihta");
cows_and_bulls();}
char[] player_number = user_guess_string.toCharArray();
char num0 = (char)random1; // casting
char num1 = (char)random2; // random numbers
char num2 = (char)random3; // into
char num3 = (char)random4; // chars
int cows = 0; // counter of instances where a number guessed by the user is in array
int bulls = 0; // counter of instances where a guessed number is in array and correct spot
for (char element : player_number) {
if (element == num0) {
cows = cows + 1;
}
}
System.out.println(cows);
}
else{ System.out.println("Not a number. Game will restart");
cows_and_bulls();}
}
I have also tried this :
for (int i = 0; i < 4; i++) {
char c = Array.getChar(player_number,i);
if (num0 == c) {
System.out.println("works");
break;
}
}
I know I am very bad at this, please help.