将数组的特定元素从一个数组移动到另一个不同大小的数组



我被要求去

创建一个具有单个参数的方法,一个整数数组,该方法将返回一个整数阵列。计算数组中存在的奇数值。用这么多元素创建一个新数组。将所有奇数值放入这个新数组中(即作为参数传递的数组中的所有奇数值(。返回此新阵列

但我在将奇数值转移到新数组中时遇到了一些困难。我可以根据第一个数组中奇数的数量得到正确的大小,但现在它们显示为零。这是代码:

import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}

根据您的问题,方法output需要…

返回此新阵列

因此方法output需要返回int[](并且而不是int(。

在对传递给方法output的数组中的奇数值进行计数并创建该方法需要返回的数组后,为了填充返回的数组,需要维护第二个[array]索引。您正在使用相同的索引来填充返回的数组并迭代数组参数。返回的数组的大小可能比数组参数小,即包含的元素更少,因此对两个数组使用相同的索引可能会导致方法output抛出ArrayIndexOutOfBoundsException。在任何方法中,还应该始终检查方法参数是否有效。

import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null  &&  beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}

您的输出函数应该返回一个数组,因此返回类型不会是int。它将是int[]。请参阅下面的代码并告诉我。

public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}

public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}

相关内容

最新更新