Nim*_*nim 5 java arrays methods
我正在用java做我的第一步,所以我的问题很简单 - 我有一个包含8个整数的数组,我想返回一个包含原始数组中奇数索引元素的数组.减速方法有什么问题?任何其他实施技巧将不胜感激.
PS - 我知道我不必在这里使用方法,它只是用于练习.
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
而且,正如Jhamon所评论的那样,你的方法名称和内部逻辑不匹配.奇数指数!=奇数值.
您的代码有问题:
- 您不能在另一个方法中定义方法。
- 如果要返回一个包含原始数组中奇数索引元素的数组。您应该检查
index%2!=0而不是检查该索引的数组值。
尝试这个
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 : " + Arrays.toString(oddIndex(arr)));
}
public static int[] oddIndex(int[] array){
int[] newArr = new int[array.length];
int j=0;
for (int i = 0; i < array.length; i++){
if ((i % 2) != 0) {
newArr[j++] = array[i];
}
}
return Arrays.copyOf(newArr, j);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
1.e odd index numbers in array : [2, 4, 6, 8] // odd index elements from original array
Run Code Online (Sandbox Code Playgroud)