如何在Java中显示数组中的特定数字?

3
我想在一行中仅列出正数,另一行中仅列出负数,但它们只能与文本逐个显示。 以下是我的代码:
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个回答

6

您目前是为每个元素打印一行(并说明它是否小于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,一个for-each循环以及(仅仅是因为)格式化输入输出来实现相同的结果。例如:

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());

3
考虑到问题本身的简单性,使用流(streams)可能超出了提问者目前的水平,所以这可能不是最好的答案。尽管如此,它仍然是有用的,所以我还是点了一个赞。;-) - Andreas
@Andreas 好观点。添加了一个使用 for-each 循环的示例。 - Elliott Frisch

4

既然您已经将值排序,那么您就知道所有负数值都在正数值之前,因此在遇到第一个正数值时开始打印值,然后切换到新行。

例如,可以处理全为负数值的数组、全为正数值的数组甚至是空数组。

这只使用了您已经展示过您知道的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

实际上,您的第二个解决方案的复杂度是 O(n),而对数组进行排序的复杂度为 O(n*log n) - Johannes Kuhn
1
@JohannesKuhn 两个版本的时间复杂度都是一样的。我的“稍微不太优化”的评论是指输出而非性能。第二个版本总是会打印两行,即使没有负数/正数值。而第一个版本只在适当的时候打印行,并用逗号分隔值,而第二个版本则不会。 - Andreas
如何在O(n)时间复杂度下对数组进行排序? - Johannes Kuhn
@JohannesKuhn 两种解决方案都是排序(_O(nlog n)_),并且都有简单的循环(_O(n)_)。从大O复杂度上来看,它们是相同的(_O(nlog n)_)。 - Andreas
啊,对了。但是第二个解决方案不需要排序。 - Johannes Kuhn
@JohannesKuhn,为了得到所需的输出,按升序列出值是必要的。如果不是为了这个,那么问题代码为什么会包括排序呢?所有其他答案都保留了排序。这也是为什么我的第一个解决方案以注释“由于您对值进行了排序,...”开头的原因。 - Andreas

3

做类似于这样的事情:

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循环之后打印它们。


2

我尽量少修改了您的代码。

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

}

2
这是流的一个完美应用案例:
System.out.println(Arrays.stream(array).filter(n -> n < 0).collect(Collectors.toList()));

0

我认为在这种情况下,使用Java 8中引入的partitioningBy方法是最合适的。您不需要对数组进行排序。

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()....

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接