gpt4 book ai didi

java - 如何返回存储在该方法中的 2 个 ArrayList,而不是仅仅将其打印在 void 中?

转载 作者:行者123 更新时间:2023-12-01 22:05:28 25 4
gpt4 key购买 nike

我只想要我的checkerOddEven()方法是 ArrayList 类型而不是 void,我希望它能够返回存储在每个变量中的两个 Arraylist,这样它就会像 void 方法的当前输出一样打印出来。

这是当前代码的输出: enter image description here

int[] numbers;

public Main(){
numbers = new int[] {1,2,3,4,5,6,7,8,9,10};
}

public boolean oddEven (int number){

if(number%2!=0){
return true;
}
return false;

}
public void checkerOddEven (int[] numbers){

ArrayList<Integer> answerOdd = new ArrayList<Integer>();
ArrayList<Integer> answerEven = new ArrayList<Integer>();

for(int number : numbers){
if(oddEven(number)){
answerOdd.add(number);
}
else answerEven.add(number);
}

System.out.println("The Odd numbers are :"+answerOdd);
System.out.println("The Even numbers are :"+answerEven);

}

public static void main(String[] args) {
Main main = new Main();

main.checkerOddEven(main.numbers);
}

最佳答案

我想这就是你想要的?

public static ArrayList<Integer>[] checkerOddEven (int[] numbers){
ArrayList<Integer> list[]; // I create an Array of ArrayLists
list = new ArrayList[2]; // I allocate memory for two ArrayLists inside that array. It's important to note that without this, trying to do list[0]=new ArrayList<>(); would have crashed, because there's no list[] yet.
list[0] = new ArrayList<>();list[1] = new ArrayList<>(); //I create the ArrayList instances by calling their constructor

for(int number : numbers){
if(oddEven(number)){
list[0].add(number);
}
else list[1].add(number);
}

return list;
}

public static void main(String[] args) {
Main main = new Main();
ArrayList<Integer>[] listOfNumbers = (checkerOddEven(main.numbers));
System.out.print("Odds: "); for(int i=0;i<listOfNumbers[0].size();i++) System.out.print(listOfNumbers[0].get(i)+" ");
System.out.println();
System.out.print("Even: "); for(int i=0;i<listOfNumbers[1].size();i++) System.out.print(listOfNumbers[1].get(i)+" ");
}

关于java - 如何返回存储在该方法中的 2 个 ArrayList,而不是仅仅将其打印在 void 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58693000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com