Как показать определенные числа из массива в Java? - PullRequest
0 голосов
/ 17 мая 2018

Я хочу выделить только положительные числа в одной строке и только отрицательные числа в одной строке, но они показывают только один за другим с текстом. Вот мой код:

int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
    Arrays.sort(array);
    for (int i = 0; i < array.length; i++) {
        if (array[i] < 0) {
            System.out.println("Less than 0: " + array[i]);

        } else if (array[i] > 0) {
            System.out.println("Greater than 0: " + array[i]);
        }

    }

Ответы [ 6 ]

0 голосов
/ 25 мая 2018

Я думаю, что использование partitioningBy (которое было введено в Java 8) именно для этой ситуации.Вам не нужно сортировать массив тоже.

Map<Boolean,List<Integer>> map = IntStream.range(0,array.length)
                .mapToObj(i->array[i])
                .collect(Collectors.partitioningBy(a->a>0));

печать положительного числа

map.get(true).forEach(integer -> System.out.print(integer+","));  

печать отрицательного числа

map.get(false).forEach(integer -> System.out.print(integer+","));  

если вы хотите отсортировать его, вы можете сделать это, как показано ниже.

map.get(false).stream().sorted()....
0 голосов
/ 18 мая 2018

Это идеальный вариант использования для потоков:

System.out.println(Arrays.stream(array).filter(n -> n < 0).collect(Collectors.toList()));
0 голосов
/ 18 мая 2018

Поскольку вы отсортировали значения, вы знаете, что все отрицательные значения предшествуют положительным значениям, поэтому вы начинаете печатать значения и затем переключаетесь на новую строку, когда встречаете первое положительное значение.

Например, как показано ниже, чтотакже может обрабатывать массив всех отрицательных значений, массив всех положительных значений и даже пустой массив.

При этом используются только те конструкции 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
0 голосов
/ 18 мая 2018

Я пытался изменить ваш код как можно меньше.

int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
boolean firstHalf = true;
System.out.print("Less than 0: ");

for (int i = 0; i < array.length; i++) {
    if (array[i] < 0) {
        System.out.print(array[i] + " ");
    } else if (array[i] > 0) {
        if (firstHalf){
            System.out.print("\nGreater than 0: ");
            firstHalf = false;
        }
        System.out.print(array[i] + " ");
    }

}
0 голосов
/ 18 мая 2018

Сделайте что-то вроде этого:

Arrays.sort(array);
String negative = "Less than 0: ";
String positive = "Greater than 0: ";
for (int i = 0; i < array.length; i++) {
    if (array[i] < 0) {
        negative.concat(array[i] + ",");
    } 
    else (array[i] > 0) {
       positive.concat(array[i] + ",");
    }
}
System.out.println(positive);
System.out.println(negative);

Сохраните значения в строке, а затем напечатайте их после цикла for.

0 голосов
/ 17 мая 2018

В настоящее время вы печатаете строку для каждого элемента (и меньше ли это 0 или больше 0), вместо этого я бы использовал IntStream и filter() для нужных элементов (и собрал бы их с Collectors.joining()). Как,

int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
System.out.println("Less than 0: " + IntStream.of(array) //
        .filter(x -> x < 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
System.out.println("Greater than 0: " + IntStream.of(array) //
        .filter(x -> x > 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));

Выходы

Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150

Вы можете достичь того же результата с парой StringJoiner (s) цикла for-each и (только потому что) отформатированного io. Как,

int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
StringJoiner sjLess = new StringJoiner(", ");
StringJoiner sjGreater = new StringJoiner(", ");
for (int x : array) {
    if (x < 0) {
        sjLess.add(String.valueOf(x));
    } else if (x > 0) {
        sjGreater.add(String.valueOf(x));
    }
}
System.out.printf("Less than 0: %s%n", sjLess.toString());
System.out.printf("Greater than 0: %s%n", sjGreater.toString());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...