0
我已經給出了我的程序到目前爲止,現在我必須使用while循環遍歷兩個數組,將它們合併到「合併」數組中,以便合併升序。而不是first.length & second.length,你應該使用countFirst & countSecond。也就是說,你應該比較indexFirst到countFirst &比較indexSecond到countSecond 我不知道如何做到這一點,所以如果能幫助我,將是巨大的如何使用while循環來合併2個數組
import java.io.*;
import java.util.*;
public class MergeArrays {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
int [] first = new int [20];
int countFirst = 0; //used to determine number of elements in "first"
int [] second = new int [20];
int countSecond = 0; //used to determine number of elements in "second"
int [] merge = new int [40];
int indexMerge = 0;
int indexFirst = 0;
int indexSecond = 0;
//open files
Scanner inFile1 = new Scanner(new File("array1.txt"));
Scanner inFile2 = new Scanner(new File("array2.txt"));
//Scanner inFile1 = new Scanner(new File("array1b.txt"));
//Scanner inFile2 = new Scanner(new File("array2b.txt"));
while (inFile1.hasNext()) {
first[countFirst] = inFile1.nextInt();
countFirst++;
}
while (inFile1.hasNext()) {
first[countFirst] = inFile1.nextInt();
countFirst++;
}
indexFirst = 0;
indexSecond = 0;
}
}
}
我相信你的第二個while循環應該在inFile2中讀入第二個[]數組。你有沒有嘗試過任何實際的合併?試着手工做兩個小陣列,以瞭解它應該如何工作。 – fjc