我正在做我在 java 中的第一步,所以我的问题很简单 - 我有一个包含 8 个整数的数组,我想返回一个包含原始数组中奇数索引元素的数组。方法减速有什么问题?任何其他实现技巧将不胜感激。
P.S - 我知道我不必在这里使用方法,它只是为了练习。
package com.tau;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
System.out.println("1.e odd index numbers in array : " + oddIndex(arr));
int j = 0;
public static int[] oddIndex(int[] array){
int newArrSize = array.length;
if ((newArrSize % 2) != 0) {
newArrSize--;
}
int[] newArr = new int[newArrSize];
for (int i = 0; i < array.length; i++)
if ((array[i] % 2) == 0) {
newArr[j] = array[i];
j++;
}
return newArr;
}
}
}
最佳答案
1)在 Java 中你不能在方法中有方法。将 oddIndex()
方法移到 main()
方法之外。
2) 并且您不能在另一个方法中使用一个方法的局部变量。所以我将你的变量 j
移动到 oddIndex()
方法
public class Main {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
System.out.println("1.e odd index numbers in array : " + oddIndex(arr));
}
public static int[] oddIndex(int[] array) {
int j = 0;
int newArrSize = array.length;
if ((newArrSize % 2) != 0) {
newArrSize--;
}
int[] newArr = new int[newArrSize];
for (int i = 0; i < array.length; i++)
if ((array[i] % 2) == 0) {
newArr[j] = array[i];
j++;
}
return newArr;
}
}
而且,正如 Jhamon 评论的那样,您的方法名称和内部逻辑不匹配。 奇数索引 != 奇数值。
关于java在方法中返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32518041/