如何用Java中的数组显示某些数字?

mar*_*ria 3 java arrays sorting numbers

我想在一行中只列出正数而在一行中只列出负数,但它们只用文本逐一显示.这是我的代码:

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

    }
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 6

您当前正在为每个元素打印一行(以及它是否小于0或大于0),而是我会使用a IntStreamfilter()它来表示所需的元素(并收集它们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(", ")));
Run Code Online (Sandbox Code Playgroud)

输出

Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
Run Code Online (Sandbox Code Playgroud)

你可以用一对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());
Run Code Online (Sandbox Code Playgroud)

  • 鉴于问题的简单性,流的使用可能超出当前的OP水平,因此这可能不是最好的答案.仍然有用,所以+1反正.;-) (2认同)