数组
来源:互联网 发布:80端口入侵 编辑:程序博客网 时间:2024/06/10 18:32
数组的定义:所谓数组,是无序的元素序列。 若将有限个类型相同的变量的集合命名,那么这个名称为数组名。组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量。用于区分数组的各个元素的数字编号称为下标,小标从0开始计算。数组是在程序设计中,为了处理方便,把具有相同类型的若干元素按无序的形式组织起来的一种形式。 这些无序排列的同类数据元素的集合称为数组。
总结:
1,数组是一片连续的内存空间
2,数组的使用
1)声明数组;-------类型 数组名[]; boolean bs[];
2)开辟内存空间-----数组名=new 类型[长度];bs=new boolean[4];
注意:1,2步可以合在一起写boolean bs[]=new boolean[4];
3)赋值--------------直接赋值,循环赋值
-----------------------------------------------------------------------
数组的直接赋值
例子:存储学生名字的数组:String names[]={"张三","李四","王五"};
练习题1:
import java.util.Arrays;
//合并两个数组
public class Test1 {
public static void main(String[] args) {
int a[]={1,2,3};
int b[]={4,5};
int c[]=new int[a.length+b.length];
for (int i = 0; i < c.length; i++) {
if (i<a.length) {
c[i]=a[i];
}
else {
c[i]=b[i-a.length];
}
}
System.out.println(Arrays.toString(c));
}
}
练习题2:
//插入排序(排序后判定要插入数据的位置,创建新数组)
public class Test2 {
public static void main(String[] args) {
int a[]={12,23,34,2,1,34,465,234,6,45};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
Scanner scr=new Scanner(System.in);
System.out.println("输入一个数字:");
int b=scr.nextInt();
int index=a.length;//设定为最大值
for (int i = 0; i < a.length; i++) {
if (b<a[i]) {
index=i;
break;//找到大于其的数值便跳出
}
}
int c[]=new int[a.length+1];
for (int i = 0; i < c.length; i++) {
if (i==index) {
c[i]=b;
}
if (i<index) {
c[i]=a[i];
}
if (i>index) {
c[i]=a[i-1];
}
}
System.out.println("新数组为:"+Arrays.toString(c));
}
}
练习题3:
import java.util.Arrays;
import java.util.Scanner;
//插入排序(先插入,再排序)
public class Test3 {
public static void main(String[] args) {
int a[]={12,23,34,2,1,34,465,234,6,45};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
Scanner scr=new Scanner(System.in);
System.out.println("输入一个数字:");
int b=scr.nextInt();
int c[]=new int[a.length+1];
for (int i = 0; i < a.length; i++) {
c[i]=a[i];
}
c[c.length-1]=b;//将插入的数据放在最后
Arrays.sort(c);//进行排序
System.out.println("新数组为:"+Arrays.toString(c));
}
}
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- Android自动解析html带图片,实现图文混排
- Unity不同脚本之间的执行顺序
- Vue DevTools可使用修正方法
- linux中Graphics2D 中文乱码的解决办法
- 正则表达式,只能输入数字且最多两位有效数字,数字位数最多五位(限制的位数可自行调整)
- 数组
- MySQL单表查询优化技巧汇总
- LeetCode-49-Group Anagrams list_to_string、string list
- HDU-6216 A Cubic number and A Cubic Number
- BeX5使用疑难总结
- NLP in English
- 数据块损坏恢复
- 数独 生成及求解
- Nmap 进阶