条件:
示例:给定setF [] = 1,2,3,4,8和setS [] = 5,6,7,它打印1,5,2,6,3,7,4,8
我的代码出现问题:它会打印并交替罚款,但如果时间更长,则不会再继续打印。
完整代码(我为稍微凌乱的格式道歉。网站搞砸了一点):
package mergearrays;
import java.io.*;
import java.lang.*;
import java.util.*;
public class MergeArrays {
public static void main(String[] args) {
//variables
boolean done = false;
boolean error = false;
int inpval = 0;
int i = 0; //will be setF.length
int j = 0; //will be setS.length
//arrays
int [] vals = new int[20000];
//ask user
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit");
//input array
Scanner scan = new Scanner(System.in);
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[i] = inpval;
i++;
}
else {
done = true;
}
}
done = false;
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit");
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[j+i+1] = inpval;
j++;
}
else {
done = true;
}
}
//new arrays
int [] setF = new int[10000];
int [] setS = new int[10000];
//copy vals into setF and setS
System.arraycopy(vals, 0, setF, 0, i);
System.arraycopy(vals, i+1, setS, 0, i+j+1);
//check for order
for (int p = 0; p < i - 1; p++) {
if (setF[p] > setF[p+1]) {
error = true;
break;
}
}
for (int b = 0; b < j - 1; b++) {
if (setS[b] > setS[b+1]) {
error = true;
break;
}
}
//print first array
System.out.print("\n First Array: ");
for(int q = 0; q < i; q++) {
System.out.print(setF[q] + " ");
}
//print second array
System.out.print("\n Second Array: ");
for(int m = 0; m < j; m++) {
System.out.print(setS[m] + " ");
}
//print the final set
if(i >= j && error == false){
System.out.print("\n Merged Array: ");
for(int n = 0; n <= i+j; n++) {
if(setF[n] != 0 && setS[n] !=0) {
if(n <= j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
}
else if(n > j && n <= i){
System.out.print(setF[n] + " ");
}
}
}
}
//error message
else {
System.out.print("\n ERROR: Array not in correct order");
}
}
}
答案 0 :(得分:1)
如果第一个数组更长,它没有继续打印的原因在于这行代码:
if (setF[n] != 0 && setS[n] != 0) {
只有当同一位置的两个阵列都为零时,才会继续打印。你应该在这里查看&#39;或者&#39;不是&#39; AND&#39;。此外,在将该条件更改为“或”之后,还需要更改内部的ifs,因为索引不正确。如下:
System.out.print("\n Merged Array: ");
for (int n = 0; n <= i + j; n++) {
if (setF[n] != 0 || setS[n] != 0) {
if (n < j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
} else if (n < i) {
System.out.print(setF[n] + " ");
}
}
}
我会以不同的方式解决它,如果你需要帮助我可以引导你。无论如何,希望这有帮助......