所以我有这个代码的问题,我有这些input.txt文件,基本上当我输入它们需要以数字顺序排序数组,但我不断得到一个逻辑错误,它只会错过一个数字。我该怎么做才能解决这个问题,或者我在哪里得到错误?我检查了我的循环和一切,只是无法搞清楚。 input3_1和input3_2 txt文件应该在java代码之前。提前感谢您的建议。
input3_1.txt = 8 3 13 5 10
input3_2.txt = 9 6 11 12 4 7 2
public class MergedArrays {
public static void main(String[] args) {
String s1, s2;
Scanner inp = new Scanner(System.in);
System.out.println("Enter File 1 name");
s1 = inp.nextLine();
System.out.println("Enter File 2 name");
s2 = inp.nextLine();
try {
int[] arr1 = new int[20];
int[] arr2 = new int[20];
int cnt = 0;
int c;
int countFirst = 0, countSecond = 0;
Scanner scanner = new Scanner(new File(s1 + ".txt"));
while (scanner.hasNext()) {
arr1[countFirst] = scanner.nextInt();
countFirst++;
}
scanner = new Scanner(new File(s2 + ".txt"));
while (scanner.hasNext()) {
arr2[countSecond] = scanner.nextInt();
countSecond++;
}
int[] merged = new int[countFirst + countSecond];
int flag1 = 0, flag2 = 0, indexMerge = 0;
int indexSecond = 0, indexFirst = 0;
int traverse1 = countFirst;
int traverse2 = countSecond;
int c2, d, swap;
for (c2 = 0; c2 < (countFirst - 1); c2++) {
for (d = 0; d < (countFirst - 1) - c2 - 1; d++) {
if (arr1[d] > arr1[d + 1]) {
swap = arr1[d];
arr1[d] = arr1[d + 1];
arr1[d + 1] = swap;
}
}
}
for (c2 = 0; c2 < (countSecond - 1); c2++) {
for (d = 0; d < (countSecond) - c2 - 1; d++) {
if (arr2[d] > arr2[d + 1]) {
swap = arr2[d];
arr2[d] = arr2[d + 1];
arr2[d + 1] = swap;
}
}
}
while (true) {
if (arr1[indexFirst] <= arr2[indexSecond]) {
merged[indexMerge] = arr1[indexFirst];
indexFirst++;
traverse1--;
} else {
merged[indexMerge] = arr2[indexSecond];
indexSecond++;
traverse2--;
}
indexMerge++;
if (traverse1 == 0) {
flag1 = 1;
break;
} else if (traverse2 == 0) {
flag2 = 1;
break;
}
}
if (flag1 == 1) {
while (indexSecond < countSecond) {
merged[indexMerge] = arr2[indexSecond];
indexMerge++;
indexSecond++;
}
} else {
while (indexFirst < countFirst) {
merged[indexMerge] = arr1[indexFirst];
indexMerge++;
indexFirst++;
}
}
int count = 0;
while (count < (countFirst + countSecond)) {
System.out.println(merged[count]);
count++;
}
} catch (Exception e) {}
}
}