我需要返回仅包含奇数的数组,例如[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]);
}
答案 0 :(得分:0)
如果要从数组中返回赔率,则应首先将其作为参数传递,也应将IF语句后的赔率存储在新数组中。 在可以轻松地将ArrayList转换为普通Array之后,由于不知道有多少几率,因此应该在第一次使用动态列表。 像这样:
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();
}
答案 1 :(得分:0)
这是您发布的代码。在下面查看我的评论
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 :(得分:0)
您可以通过本机Java 8流API节省时间:
int[] odds = Arrays.stream(arrayOfNumbers).filter(number -> number%2 != 0).toArray();
Streams提供了许多方法来使您的工作迅速