【问题标题】:How to show certain numbers from an Array in Java?如何在Java中显示数组中的某些数字?
【发布时间】:2018-10-28 05:55:52
【问题描述】:

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

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

    }

【问题讨论】:

    标签: java arrays sorting numbers


    【解决方案1】:

    您当前正在为每个元素打印一行(以及它是否小于 0 或大于 0),而不是我将使用 IntStreamfilter() 它作为所需的元素(并使用 @987654323 收集这些元素@)。喜欢,

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

    【讨论】:

    • 鉴于问题的简单性,流的使用可能超出了当前的 OP 水平,因此这可能不是最好的答案。仍然有用,所以无论如何+1。 ;-)
    • @Andreas 好点。添加了另一个带有 for-each 循环的示例。
    【解决方案2】:

    做这样的事情:

    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 循环之后打印出来。

    【讨论】:

      【解决方案3】:

      我尝试尽可能少地更改您的代码。

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

      【讨论】:

        【解决方案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)
        • @JohannesKuhn 两者都有相同的 Big-O。我的“稍微不太理想”的评论是指输出,而不是性能。第二个版本将始终打印 2 行,即使没有负/正值。第一个版本只在适当的时候打印行,并用逗号分隔值,而第二个版本没有。
        • O(n)中的数组进行排序?
        • @JohannesKuhn 两种解决方案都排序 (O(n*log n)),并且都有简单的循环 (O(n))。 Big-O 复杂度方面,它们是相同的 (O(n*log n))。
        • 啊,对。但是第二种解决方案不需要排序。
        【解决方案5】:

        这是流的完美用例:

        System.out.println(Arrays.stream(array).filter(n -> n < 0).collect(Collectors.toList()));
        

        【讨论】:

          【解决方案6】:

          我认为使用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()....
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-08-08
            • 2019-05-31
            • 1970-01-01
            • 2015-09-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多