我正在尝试完成一项家庭作业,我的任务是在不使用 sort() 函数或任何其他预定义方法的情况下将排序数组组合成一个排序数组。
我的代码如下:
try {
// get input from a file
Scanner ourScanner = new Scanner(new File(fileName));
int numInArray1;
int numInArray2;
int [] array1 = null;
int [] array2 = null;
int [] array3 = null;
int indexArray1 = 0;
int indexArray2 = 0;
int indexArray3 = 0;
boolean run = true;
// keep looking for more input
while (ourScanner.hasNext()) {
numInArray1 = ourScanner.nextInt(); // first int will be number of elements in array
array1 = new int[numInArray1]; // create array1 with proper quantity of space allocated
for (int i = 0; i < numInArray1; i++) { // puts certain number of int into the array as indicated by numInArray1
array1[i] = ourScanner.nextInt();
}
numInArray2 = ourScanner.nextInt(); // next int after the integers put in the array will be number of elements in array2
array2 = new int[numInArray2]; // create array2 with proper quantity of space allocated
array3 = new int[numInArray1 + numInArray2]; // create final array for both lists merged, allocate appropriate amount of space
for (int j = 0; j < numInArray2; j++) { // puts certain number of int into the second array as indicated by numInArray2
array2[j] = ourScanner.nextInt();
}
//.out.println(Arrays.toString(array1));
//System.out.println(Arrays.toString(array2));
}
/*System.out.println(Arrays.toString(array1));
System.out.println(Arrays.toString(array2));*/
while (run == true) {
if (array1.length - indexArray1 == 1 && array2.length - indexArray2 == 1) {
run = false;
}
我的代码在第一个数组大于第二个时工作,但是当第一个数组小于第二个时我收到错误。
我不确定为什么会发生这种情况,因此将不胜感激任何朝正确方向的指导或推动。
慕妹3242003
慕姐8265434
相关分类