Hallo, ich wollte eine Methode schreiben die 2 Arrays vergleicht und die zahlen, die
insgesamt genau einmal vorkommen im int[] array returnen.
Ich habe was versucht und zwar erst mal die Arrays nach Größe sortiert und dann wollte ich die vergleichen, was aber nicht genau hinkommt. Hat jemand eine Idee ?
z.B:
int[] a = {2,7,4,-3};
int[] b = {3,1,2,3};
= {-3,1,4,7}
insgesamt genau einmal vorkommen im int[] array returnen.
Ich habe was versucht und zwar erst mal die Arrays nach Größe sortiert und dann wollte ich die vergleichen, was aber nicht genau hinkommt. Hat jemand eine Idee ?
z.B:
int[] a = {2,7,4,-3};
int[] b = {3,1,2,3};
= {-3,1,4,7}
Java:
public static void main(String[] args){
int[] a = {2,7,4,-3};
int[] b = {3,1,2,3};
for(int i = 0; i < once(a,b).length; i++){ // array ausgeben
System.out.print(once(a,b)[i] + " ");
}
System.out.println();
}
public static int[] once(int[] a, int[] b){
a = sortier(a);
b = sortier(b);
for(int i = 0; i < a.length; i++){ // vergleichen
for(int j = 0; j < b.length-1 ; j++){
if(a[i] == b[j]){
a[i] = b[j+1];
}
}
}
return a;
}
// nach größe sortieren
public static int[] sortier(int[] x){
int temp;
for(int i = 1; i < x.length; i++){
for(int j = 0; j < x.length - i; j++){
if(x[j] > x[j+1]){
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}
return x;
}
Code:
Ausgabe:
-3 3 4 7