How to initialize an array in Java?

后端 未结 10 1965
天命终不由人
天命终不由人 2020-11-22 00:23

I am initializing an array like this:

public class Array {

    int data[] = new int[10]; 
    /** Creates a new instance of Array */
    public Array() {
           


        
相关标签:
10条回答
  • 2020-11-22 01:00

    Rather than learning un-Official websites learn from oracle website

    link follows:Click here

    *You can find Initialization as well as declaration with full description *

    int n; // size of array here 10
    int[] a = new int[n];
    for (int i = 0; i < a.length; i++)
    {
        a[i] = Integer.parseInt(s.nextLine()); // using Scanner class
    }
    

    Input: 10//array size 10 20 30 40 50 60 71 80 90 91

    Displaying data:

    for (int i = 0; i < a.length; i++) 
    {
        System.out.println(a[i] + " ");
    }
    

    Output: 10 20 30 40 50 60 71 80 90 91

    0 讨论(0)
  • 2020-11-22 01:02

    you are trying to set the 10th element of the array to the array try

    data = new int[] {10,20,30,40,50,60,71,80,90,91};
    

    FTFY

    0 讨论(0)
  • 2020-11-22 01:04
    data[10] = {10,20,30,40,50,60,71,80,90,91};
    

    The above is not correct (syntax error). It means you are assigning an array to data[10] which can hold just an element.

    If you want to initialize an array, try using Array Initializer:

    int[] data = {10,20,30,40,50,60,71,80,90,91};
    
    // or
    
    int[] data;
    data = new int[] {10,20,30,40,50,60,71,80,90,91};
    

    Notice the difference between the two declarations. When assigning a new array to a declared variable, new must be used.

    Even if you correct the syntax, accessing data[10] is still incorrect (You can only access data[0] to data[9] because index of arrays in Java is 0-based). Accessing data[10] will throw an ArrayIndexOutOfBoundsException.

    0 讨论(0)
  • 2020-11-22 01:07

    When you create an array of size 10 it allocated 10 slots but from 0 to 9. This for loop might help you see that a little better.

    public class Array {
        int[] data = new int[10]; 
        /** Creates a new instance of an int Array */
        public Array() {
            for(int i = 0; i < data.length; i++) {
                data[i] = i*10;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:08

    You can do:

    int[] data = {10,20,30,40,50,60,71,80,90,91};
    
    0 讨论(0)
  • 2020-11-22 01:10

    Maybe this will work:

    public class Array {
    
        int data[] = new int[10]; 
        /* Creates a new instance of Array */
        public Array() {
            data= {10,20,30,40,50,60,71,80,90,91};
        }
    }
    
    0 讨论(0)
提交回复
热议问题