gpt4 book ai didi

java - java中反转两个输入数组

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

如何反转此代码?我以为我正在使用正确的方法来反转这个数组,但它仍然不起作用......

我希望有人能帮助我。 tq

所以,这是我的代码:

import java.util.Scanner ;

public class ArrayYear
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int[] arr = new int[3];
int[] year = new int[3];

//read element into array
for ( int i=0 ; i <= arr.length ; i++ )
{
arr[i] = in.nextInt() ; // input value

for ( int j=0 ; j<=arr.length/2 ; j++ ){

int temp = arr[j];
arr[j] = arr[arr.length - i - 1 ];
arr[arr.length - i - 1 ] = temp;
}

year[i]= in.nextInt();

System.out.println( "ID :" + arr[i] + "("+ year[i] +")" ) ;
}
}
}

注意:需要反转的数组只是第一个数组arr[i]

最佳答案

您必须先填充数组,然后反转它,并且循环应达到 i<=arr.length-1 .反转数组代码将是

public static int[] reverseArray(int a[]) {

int b[] = new int[a.length];
int index = 0;
for (int i = a.length - 1; i >= 0; i--)
b[index++] = a[i];

return b;
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System. in );
int c[] = new int[5];
int index = 0;
while (sc.hasNextLine()) {
c[index++] = Integer.parseInt(sc.nextLine().trim());
}
System.out.println("Before Reverse " + Arrays.toString(c));
System.out.println("After Reverse " + Arrays.toString(reverseArray(c)));
}

输入

1
2
3
4
5

输出

Before Reverse [1, 2, 3, 4, 5]
After Reverse [5, 4, 3, 2, 1]

Demo

关于java - java中反转两个输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33332869/

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