gpt4 book ai didi

java - 输入2个整数数组并打印交替元素

转载 作者:行者123 更新时间:2023-12-01 09:12:09 25 4
gpt4 key购买 nike

条件:

  1. 两个数组必须按顺序排列或出现错误消息
  2. 第一个数组必须与第二个或错误消息一样长或更长
  3. 如果第一个比第二个长,则必须继续打印第一个

示例:给定 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");
}
}
}

最佳答案

如果第一个数组较长,它不会继续为您打印的原因在于这行代码:

if (setF[n] != 0 && setS[n] != 0) {

仅当同一位置的两个数组均为零时,您才继续打印。您应该在此处检查“OR”而不是“AND”。另外,将该条件改为“OR”后,里面的if也需要更改,因为索引不正确。如下:

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] + " ");
}
}
}

我会用不同的方式解决这个问题,如果您需要帮助,我可以指导您。无论如何,希望这有帮助......

关于java - 输入2个整数数组并打印交替元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40851176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com