[英]Am using Gson with freemarker template. When i try to check an array object as null then am getting error
[英]I am getting an error when reversing an array by iterating it till half
我試圖通過將數組運行到一半來反轉數組,以便如果它有奇數個元素,則中間的元素被省略,因為它不需要交換,如果是偶數,則每個元素都將被交換,但我沒有知道我錯在哪里。
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
int[] arr = new int[x];
for(int i = 0 ; i < arr.length ; i++)
{
arr[i] = scn.nextInt();
}
int temp = x;
for(int i = 0 ; i < temp / 2 ;i++)
{
int temp1 = arr[i];
arr[i] = arr[x - 1];
arr[x - 1] = temp1;
x--;
}
for(int z=0;z<arr.length;z++)
{
System.out.println(arr[z]);
}
}
}
你的嘗試非常接近。 請參閱以下更改。
for(int i = 0 ; i < temp / 2 ;i++)
{
int temp1 = arr[i];
arr[i] = arr[x - 1]; // should be arr[x - i - 1]
arr[x - 1] = temp1; // should be arr[x - i - 1]
x--; // delete this line
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.