有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java只返回奇数数组

我只需要返回一个奇数数组,例如[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]);
}

共 (1) 个答案

  1. # 1 楼答案

    这是你发布的代码。见下面我的评论

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