Detailed explanation of Java one-dimensional array: Java creates one-dimensional array, initializes one-dimensional array, and obtains single / all elements

Create a one-dimensional array

数据类型数组名[];    //声明数组
数据类型[]数组名;    //声明数组
int[] score;    //存储学生的成绩,类型为整型
double[] price;    //存储商品的价格,类型为浮点型
String[] name;    //存储商品名称,类型为字符串型
int score[10];    //这是错误的

Allocate space

数组名=new 数据类型[数组长度];    //分配空间
score=new int[10];
price=new double[30];
name=new String[20];
数据类型[]数组名=new 数据类型[数组长度];

Example 1

int arr=new int[5];

Initialize a one-dimensional array

Initialize after specifying the array size with new

type[] array=new int[size];

Example 2

int[] number=new int[5];
number[0]=1;
number[1]=2;
number[2]=3;
number[3]=5;
number[4]=8;

Use new to specify the value of the array element

type[] array=new type[]{值 1,值 2,值 3,值 4,• • •,值 n};

Example 3

int[] number=new int[]{1,2,3,5,8};

Directly specify the value of the array element

type[] array={值 1,值 值 n};

Example 4

int[] number={1,8};
int[] number;
number={1,8};

Get a single element

array[index];

Example 5

int[] number={1,8};
System.out.println("获取第一个元素:"+number[0]);
System.out.println("获取最后一个元素:"+number[number.length-1]);
获取第一个元素:1
获取最后一个元素:8

Example 6

import java.util.Scanner;
public class Test06
{
    public static void main(String[] args)
    {
        int[] prices=new int[5];    //声明数组并分配空间
        Scanner input=new Scanner(system.in);    //接收用户从控制台输入的数据
        for(int i=0;i<prices.length;i++)
        {
            System.out.println("请输入第"+(i+1)+"件商品的价格:");
            prices[i]=input.nextInt();    //接收用户从控制台输入的数据
        }
        System.out.println("第 3 件商品的价格为:"+prices[2]);
    }
}
请输入第1件商品的价格:
5
请输入第2件商品的价格:
4
请输入第3件商品的价格:
6
请输入第4件商品的价格:
4
请输入第5件商品的价格:
8
第 3 件商品的价格为:6

Get all elements

int[] number={1,8};
for (int i=0;i<number.length;i++)
{
    System.out.println("第"+(i+1)+"个元素的值是:"+number[i]);
}
for(int val:number)
{
    System.out.print("元素的值依次是:"+val+"\t");
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>