I've got a question to my program:
public class Muster2 {
int[] farben;
constructs an array with 4 integers
public Muster2(int f0, int f1, int f2, int f3) {
int[] farben = new int[4];
farben[0] = f0;
farben[1] = f1;
farben[2] = f2;
farben[3] = f3;
}
casts this array into a String
public String toString() {
String result = "";
for (int i=0;i<4;i++) {
char convert = (char) farben[i];
result+=convert;
}
return result;
}
The Idea: At first, I want to see where the two Arrays have the same integer at the same position: Example: [1,2,3,4] and [1,4,5,6]. The counter_weiss should be = 1 for those two arrays, cause only the element at position 0 is the same for both arrays. So counter_weiss counts the elements, which are the same at exactly the same position in both arrays. The counter_schwarz counts the elements, which exist in both arrays, but on other positions. So counter_schwarz would be = 1 too, for the given arrays, cause in the first we have 4 at position 3 and in the second array there we can find the 4 at the second position.
public Bewertung bewerte(Muster versuch) {
int counter_schwarz = 0;
int counter_weiss = 0;
They have to be 0 at first
for (int i=0;i<4;i++) {
I run through the array
if (this.farben[i] != versuch.farben[i]) {
and check if I got the same elements in the same position
for (int o=i+1;o<4;i++) {
if not, i check if i have it on another position, but i have to start with o at i+1, cause otherwise I would count things twice when I get to an index at the end of the array like i=3. Lets say 0,3 is a possible combination, so the first element of the first array has the same number like the second on position 3. Then counter_schwarz would get +1 from 0,3 and also from 3,0.
if(this.farben[i] == versuch.farben[o]) {
counter_schwarz += 1;
}
}
}
else counter_weiss +=1;
}
if the elements at the same position are the same, counter_white gets +1
Bewertung aktuelleBewertung = new Bewertung (counter_schwarz, counter_weiss);
return aktuelleBewertung; /* here the counters are used to construct an object,
which doesn't matter now, this part should work fine */
}
public static void main (String[] args) {
Muster Muster1 = new Muster (1,2,3,4);
Muster Muster2 = new Muster (2,3,4,5);
Bewertung Neu = Muster1.bewerte(Muster2);
System.out.println(Neu.toString());
}
}
The Problem now is, that I get a NullPointerException at
if (this.farben[i] != versuch.farben[i])
I don't know why, can anybody help me?
Thanks