I need to write code that will write all negative and positive numbers from array, i did that, other part of code is to write all duplicate numbers and how many times do they repeat , it works, but it also writes error, im new to java, so if anyone can help with my code, thank you
public static void main(String[] args) {
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int cntPoz = 0, cntNeg = 0;
//for petlja broji pozitivne i negativne clanove array-a
for (int a = 0; a < array.length; a++) {
if (array[a] > 0) {
cntPoz++;
} else if (array[a] < 0) {
cntNeg++;
}
}
// kreiranje novih nizova
int[] pArr = new int[cntPoz];
int[] nArr = new int[cntNeg];
//for petlja iz array-a premjesta sve pozitivne brojeve
cntPoz = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
pArr[cntPoz++] = array[i];
}
}
//for petlja iz array-a premjesta sve negativne brojeve
cntNeg = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
nArr[cntNeg++] = array[i];
}
}
//sortiranje i ispis nizova
Arrays.sort(pArr);
Arrays.sort(nArr);
System.out.println("Originalni niz je : \n" + java.util.Arrays.toString(array) + "\n");
System.out.println("Niz pozitivnih brojeva : \n" + java.util.Arrays.toString(pArr) + "\n");
System.out.println("Niz negativnih brojeva : \n" + java.util.Arrays.toString(nArr));
System.out.println();
System.out.println();
int[] arr2 = new int[array.length];
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
arr2[i]++;
if (i + 1 < array.length) {
if (array[i] == array[i + 1]) {
arr2[i]++;
i++;
}
}
}
for (int j = 0; j<array.length; j++){
for (int i = j+1; i < array.length; i++) {
if (arr2[i] > 0 && array[i]==array[i+1]) {
System.out.println("Duplikati su : "+array[i] + " i pojavljuju se " + arr2[i]);
}
}
System.out.println(Arrays.toString(array));
}
Aucun commentaire:
Enregistrer un commentaire