2015-11-30 30 views
-3

任何人都可以請告訴爲什麼正義的方式將工作,而不是其他方式。任何其他方式使用前初始化int []

另外,如果我想在運行時製作數組大小,我是否可以使它無論如何。

public class RevesingSimpleArray { 

    public static void main(String[] args) { 
     int[] arr = { 1, 2, 3, 4, 5 }; 
     // 1 way will work 
     int[] arr2 = { 0, 0, 0, 0, 0 }; 
     // 2 way not work 
     // int[] arr2 = {}; 
     // 3 way not work 
     // int[] arr2 = null; 

     for (int i = 0; i < arr.length; i++) { 
      System.out.println(arr[i]); 
      arr2[arr.length - (i + 1)] = arr[i]; 
     } 
     System.out.println(" leangth " + arr.length); 

     System.out.println("Printing into reverse form --"); 
     for (int j = 0; j < arr2.length; j++) { 
      System.out.println(arr2[j]); 
     } 
    } 
} 

我是新來的java,並嘗試瞭解一些基礎知識。 感謝您的幫助提前。

+1

JLS(https://docs.oracle.com/javase/specs/)將幫助你 – Andremoniy

+3

INT [] = ARR2新INT [5];也許你正在尋找這個... –

+0

謝謝@andre它真的有幫助 –

回答

1
// int[] arr2 = {}; // actually it gives `ArrayIndexOutOfBoundsException` 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 

您需要訪問之前,數組初始化它通過索引元素

// int[] arr2 = null; // actually it gives `NullPointerException` 
Exception in thread "main" java.lang.NullPointerException 

您需要初始化在訪問它的函數之前訪問數組

任何人都可以請告訴爲什麼正義的方式將工作,而不是其他人。

以下是幾種方法。

int[] myIntArray = new int[3]; 
int[] myIntArray = {1,2,3}; 
int[] myIntArray = new int[]{1,2,3}; 

另外,如果我想在運行時,使數組的大小,我將能夠使它 反正。

是的,像這樣的東西,獲取大小和初始化時分配。

public static void main(String[] args) { 
     Scanner n = new Scanner(System.in); 
     int ne = 0; 
     System.out.print("Enter Number of Elements to create array with"); 
     ne = n.nextInt(); 
     int num[] = new int[ne]; 
    } 
+0

爲什麼其他方式不工作 - int [] arr2 = {}; int [] arr2 = null; ,我已經嘗試過了,請你解釋一下。 –

+0

@Avenger什麼是問題,看起來不錯,沒有編譯問題。 –

+0

在這兩個初始化我在評論中提到已完成,但我有錯誤空指針,但爲什麼它是原始數據類型的數組不是包裝類的類型,所以爲什麼我在這種情況下有空指針。 –

1

你是能夠使陣列在運行時:

int size = 5; 
int[] array = new int[size]; 
+0

你的'x'從哪裏來, –