【发布时间】:2019-06-25 03:45:22
【问题描述】:
我已经尝试了近三个小时来解决这个练习,但我仍然不明白我做错了什么。我应该将两个带有数字的 ArrayList 合并为一个,但问题是,它们必须像这样排序:
如果 arraylist "A" 有数字 [1, 2, 3] 并且 arraylist "B" 有 [9, 8, 7, 6, 5] 那么 ArrayList "merge" 应该是 [1, 9, 2, 8 , 3, 7, 6, 5]。
也就是说,它应该交替输入数组列表 A 和 B 中的数字。如果一个数组列表更长,它应该继续填充数字(就像在这种情况下 [7,6,5] 发生的情况。 此外,我们不知道任何数组列表的长度。
这是我认为应该很好用的一种解决方案,但我无法让它发挥作用。 非常感谢所有帮助!
import java.util.ArrayList;
import java.util.Scanner;
public class test19 {
public static void main(String[] args) {
ArrayList<Integer> arrayListA = new ArrayList<>();
ArrayList<Integer> arrayListB = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Write a number to place in ArrayList A, quit with '-1'");
int Local = sc.nextInt();
if(Local > 0) {
arrayListA.add(Local);
} else {
break;
}
}
System.out.println();
System.out.println();
while(true) {
System.out.println("Write a number to place in ArrayList B, quit with '-1'");
int Local = sc.nextInt();
if(Local > 0) {
arrayListB.add(Local);
} else {
break;
}
}
System.out.println(merge(arrayListB, arrayListA));
}
public static ArrayList<Integer> merge(ArrayList<Integer> a, ArrayList<Integer> b) {
ArrayList<Integer> merge = new ArrayList<>();
if(a.size() < b.size()) {
//here we check which list is the smallest and use that one (so we don't try to add blankspaces from the longer list to the merge list)
for(int i = 0; i <= a.size(); i++) {
merge.add(a.get(i));
merge.add(b.get(i));
}
for(int j = a.size(); j <= b.size(); j++) {
merge.add(b.get(j)); //here we add the leftover numbers to the list
}
} else { //this means that list A is bigger than list B
for(int i = 0; i <= b.size(); i++) {
merge.add(a.get(i));
merge.add(b.get(i));
}
for(int j = b.size(); j <= a.size(); j++) {
merge.add(b.get(j));
}
}
return merge;
}
}
【问题讨论】:
-
j<=a.size()应该是j<a.size()(以及其他类似情况)。实际上,您的代码有很多问题。主要是你在几个地方混淆了 a 和 b。