首页 > 解决方案 > 如何在 Java 中显示数组中的某些数字?

问题描述

我想在一行中只挑出正数,在一行中只挑出负数,但它们只与文本一一显示。这是我的代码:

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]);
        }

    }

标签: javaarrayssortingnumbers

解决方案


您当前正在为每个元素打印一行(以及它是否小于 0 或大于 0),而不是我将使用 anIntStreamfilter()it 用于所需的元素(并使用 收集那些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());

推荐阅读