Поскольку вы отсортировали значения, вы знаете, что все отрицательные значения предшествуют положительным значениям, поэтому вы начинаете печатать значения и затем переключаетесь на новую строку, когда встречаете первое положительное значение.
Например, как показано ниже, чтотакже может обрабатывать массив всех отрицательных значений, массив всех положительных значений и даже пустой массив.
При этом используются только те конструкции Java, которые вы уже знаете.
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
for (int i = 0, iFirstPositive = 0; i < array.length; i++) {
if (array[i] < 0)
iFirstPositive = i + 1; // Assume index of first positive value is next
if (i == iFirstPositive) {
if (i != 0)
System.out.println(); // End line of negative values
System.out.print("Greater than 0: "); // Start line of positive values
} else if (i == 0) {
System.out.print("Less than 0: "); // Start line of negative values
} else {
System.out.print(", ");
}
System.out.print(array[i]);
}
if (array.length != 0) {
System.out.println(); // End line if anything printed
}
Вывод
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
Проще, но чуть менее оптимально, вы также можете просто сделать это с двумя циклами:
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
System.out.print("Less than 0:");
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.print(" " + array[i]);
}
}
System.out.println();
System.out.print("Greater than 0:");
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
System.out.print(" " + array[i]);
}
}
System.out.println();
Выход
Less than 0: -50 -5 -2
Greater than 0: 2 4 12 54 150