Java self - Array creation Array

How to create a Java array

Array is a fixed length, comprising a container of the same type of data

Step 1: declare an array

int [] a; declares an array variable.
[] Indicates that the variable is an array
int array representing where each element is an integer
a is a variable name
, however, this is just a statement, not create arrays

Sometimes written as int a []; there is no difference, what you see is pleasing to the eye problem

public class HelloWorld {
    public static void main(String[] args) {
        // 声明一个数组
        int[] a;
    }
}

Step 2: Creating an array

Create an array of time, to indicate the length of the array.
new int [5]
cited concept:
If a variable representing an array, such as a, we have referred to a reference
with a different basic types
int c = 5; c assigned to the called 5
declare a reference int [] a;
a = new new int [5];
make this a reference point to an array
Creating an array

public class HelloWorld {
    public static void main(String[] args) {
        //声明一个引用
        int[] a;
        //创建一个长度是5的数组,并且使用引用a指向该数组
        a = new int[5];
         
        int[] b = new int[5]; //声明的同时,指向一个数组
         
    }
}

Step 3: Access Array

Yl array subscript 0
subscripts 0, representative of a first number of the array
Access Array

 public class HelloWorld {
        public static void main(String[] args) {
            int[] a;
            a = new int[5];
             
            a[0]= 1;  //下标0,代表数组里的第一个数
            a[1]= 2;
            a[2]= 3;
            a[3]= 4;
            a[4]= 5;
        }
    }

Step 4: the array length

.length length attribute used to access an array of
array access index range is from 0 to length - 1
Outside this range, it will produce an array subscript bounds exception

Array length

public class HelloWorld {
    public static void main(String[] args) {
        int[] a;
        a = new int[5];
         
        System.out.println(a.length); //打印数组的长度
         
        a[4]=100; //下标4,实质上是“第5个”,既最后一个
        a[5]=101; //下标5,实质上是“第6个”,超出范围 ,产生数组下标越界异常
         
    }
}

Exercise : Array minimum

(First create an array of length 5
and then to every given an array of random integers
for loop, through the array to find a minimum value out

Random integer of 0-100 access to a variety of ways, is one of the following reference method:

(int) (Math.random() * 100)

Math.random () will be a random floating point number between 0-1, and then multiplied by 100, and can be strong into integer. )
Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/jeddzd/p/11387679.html