【问题标题】:Returning an array of only odd numbers返回一个只有奇数的数组
【发布时间】:2019-12-12 17:16:49
【问题描述】:

我需要返回一个只有奇数的数组,例如[1,3,5]。作为学校教育的一部分,我被要求这样做,但我看不出哪里出错了。

public static int[] odds(int numOdds) {
    int[] odds = numOdds;
    for (int i=0; i<odds.length; i++) {
        if (odds[i] %2 != 0) {
            return odds;
        }
    }
}

public static void main(String[] args) {
    int[] theOdds = odds(3);
    System.out.println(theOdds[0] + ", " + theOdds[1] + ", " + theOdds[2]);
}

【问题讨论】:

  • 编译器错误信息说什么?你读过吗?将 int 存储在类型不是 int 而是 int[] 的变量中听起来不错吗?您的代码从不在数组中存储任何内容看起来正常吗? docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
  • 您将一个整数分配给一个整数数组。改为int[] odds = new int[numOdds];
  • 编译器甚至可以准确地告诉您出了什么问题。如果您在遇到麻烦的第一个迹象时举手,那么您将永远不会学到任何东西。为了学习,与问题作斗争很重要。
  • 您正在将 int 值传递给该方法。你想要前三个奇数吗?或者你想传递一个带有一些数字的整数数组并只从中选择奇数。请在您的问题中澄清这一点。
  • 感谢您的 cmets。我一直在读它,我只是无法理解它,我的“导师”并没有真正给我时间解释让我理解。 numOdds 实际上是一个正整数,表示我必须存储在数组中的奇数个数

标签: java arrays methods


【解决方案1】:

这是您发布的代码。见下面我的cmets

public static int[] odds(int numOdds) {
    //   int[] odds = numOdds;     // needs to be int[] odds = new int[numOdds] to 
                                   //store the values.  It is the array you will 
                                   // return.
    int[] odds = new int[numOdds];

    int start = 1;            // you need to have a starting point
    for (int i=0; i<odds.length; i++) {
    //    if (odds[i] %2 != 0) { // don't need this as you are generating odd 
                                 // numbers yourself


    //    return odds;      // You're doing this too soon.  You need to store 
                               // the numbers in the array first 

          odds[i] = start;  // store the first odd number
          start += 2;       // this generates the next odd number.  Remember that
                            // every other number is even or odd depending from
                            // where you start.

    }
    return odds;         // now return the array of odd numbers.

    }
}

public static void main(String[] args) {
    int[] theOdds = odds(3);
    System.out.println(theOdds[0] + ", " + theOdds[1] + ", " + theOdds[2]);
}

【讨论】:

  • 你为此。解释对我来说非常好,可以理解我在这里所缺少的理性。非常感谢
【解决方案2】:

如果你想从一个数组返回赔率,你应该首先将它作为参数传递,并且你应该在 IF 语句之后将你的赔率存储在一个新数组中。 你应该在第一次使用动态列表,因为你不知道有多少几率,在你可以轻松地将 ArrayList 转换为普通数组之后。 像这样的:

public static int[] odds(int[] arrayOfNumber) {

List<Integer> odds = new ArrayList<Integer>();

for (int i=0; i<arrayOfNumber.length; i++) {
    if (arrayOfNumber[i] %2 != 0) {
        odds.add(arrayOfNumber[i]);
    }
  }
  return odds.toArray();
}

【讨论】:

    【解决方案3】:

    您可以通过本机 Java 8 流 API 以这种方式节省时间:

    int[] odds = Arrays.stream(arrayOfNumbers).filter(number -> number%2 != 0).toArray();
    

    Streams 提供了多种方法让您的工作快速完成

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 2012-01-01
      • 2011-11-05
      • 2020-09-03
      • 2022-11-15
      • 2019-07-21
      • 2015-06-26
      • 2021-08-22
      • 2016-10-21
      相关资源
      最近更新 更多