文章目录
1.数组的定义2.数组元素赋值3.访问数组元素4.数组最值5.数组排序6.二维数组
1.数组的定义
int[] x
;
x
=new int[10];
相当于
int[] x
=new int[10];
2.数组元素赋值
package java自学博客
;
public class Java数组
{
public static void main(String
[] args
) {
int[] x
= {0,1,2,3};
int[] y
=new int[4];
y
[0]=0;
y
[1]=1;
y
[2]=2;
y
[3]=3;
}
}
3.访问数组元素
package java自学博客
;
public class Java数组
{
public static void main(String
[] args
) {
int[] x
= {0,1,2,3};
int[] y
=new int[4];
y
[0]=0;
y
[1]=1;
y
[2]=2;
y
[3]=3;
for(int i
=0;i
<x
.length
;i
++) {
System
.out
.println(x
[i
]);
}
System
.out
.println("数组x的长度是:"+x
.length
);
for(int i
=0;i
<y
.length
;i
++) {
System
.out
.println(y
[i
]);
}
System
.out
.println("数组y的长度是:"+y
.length
);
}
}
--------------------------------
0
1
2
3
数组x的长度是
:4
0
1
2
3
数组y的长度是
:4
4.数组最值
package java自学博客
;
public class Java数组
{
public static void main(String
[] args
) {
int[] x
= {5,2,1,1,3,1,4};
int max
=getMax(x
);
System
.out
.println("Max="+max
);
}
static int getMax(int[] x
) {
int max
=x
[0];
for(int i
=0;i
<x
.length
;i
++) {
if(x
[i
]>max
)
max
=x
[i
];
}
return max
;
}
}
------------
Max
=5
package java自学博客
;
public class Java数组
{
public static void main(String
[] args
) {
int[] x
= {5,2,1,1,3,1,4};
int min
=getMin(x
);
System
.out
.println("Min="+min
);
}
static int getMin(int[] x
) {
int min
=x
[0];
for(int i
=0;i
<x
.length
;i
++) {
if(x
[i
]<min
)
min
=x
[i
];
}
return min
;
}
}
-----------------
Min
=1
5.数组排序
package java自学博客
;
public class Java数组
{
public static void main(String
[] args
) {
int[] x
= {5,2,1,1,3,1,4};
System
.out
.println("排序前:");
printArray(x
);
bubbleSort(x
);
System
.out
.println("\n排序后:");
printArray(x
);
}
public static void printArray(int[] x
) {
for(int i
=0;i
<x
.length
;i
++) {
System
.out
.print(x
[i
]+" ");
}
}
public static void bubbleSort(int[] x
) {
for(int i
=0;i
<x
.length
-1;i
++) {
for(int j
=0;j
<x
.length
-1-i
;j
++)
if(x
[j
]>x
[j
+1]) {
int t
=x
[j
];
x
[j
]=x
[j
+1];
x
[j
+1]=t
;
}
}
}
}
------------------
排序前
:
5 2 1 1 3 1 4
排序后
:
1 1 1 2 3 4 5
6.二维数组
package java自学博客
;
public class Java数组
{
public static void main(String
[] args
) {
int[][] x
= new int[3][];
x
[0]=new int[] {00,01,02};
x
[1]=new int[] {10,11,12};
x
[2]=new int[] {20,21,22};
for(int i
=0;i
<x
.length
;i
++) {
for(int j
=0;j
<x
[i
].length
;j
++) {
System
.out
.print(x
[i
][j
]+" ");
}
System
.out
.print("\n");
}
}
}
-------------
0 1 2
10 11 12
20 21 22
转载请注明原文地址:https://blackberry.8miu.com/read-14719.html