数组是一个变量,存储相同数据类型的一组数据
数组的基本要素:
标识符:数组的名称
数组元素:数组中存放的数据
元素下标:对数组元素进行编号,数组下标从0开始,数组中的每个元素都可以通过下标来访问
元素类型:数组元素的数据类型
声明并赋值的两种方法:
int[ ] scores = new int[ ]{89, 79, 76};
int[ ] scores = {89, 79, 76};
动态地从键盘录入信息并赋值
Scanner input = new Scanner(System.in);
for(int i = 0; i < 30; i ++){
score[i] = input.nextInt();
}
数组的应用
添加元素
package com.base.day11;
public class Delbooks {
public static void main(String[] args) {
String[] books={"三国演义","红楼梦", "史记" , "西游记", "左传","菜根谭"};
for (int i = 0; i < books.length; i++) {
if ("左传".equals(books[i])){
for (int j = i;j < books.length - 1;j++){
books[j] = books[j + 1];
}
// break;
books[5] = null;
}
System.out.println(books[i]);
}
}
}
声明该数组
通过比较找到插入位置(下标)
将增加的手机名称插入到该位置
修改元素
package com.base.day11;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
int numInput = sc.nextInt();
int[] num = {8, 4, 2, 1, 23, 344, 12};
int sum = 0;
for (int i = 0; i < num.length; i++) {
sum += num[i];
//循环输出所有值
System.out.println(num[i]);
}
System.out.println("****************************************");
//求和
System.out.println(sum);
System.out.println("****************************************");
//判断打印有无此数
boolean number = true;
for (int i = 0; i < num.length; i++) {
if (numInput == num[i]) {
number = true;
System.out.println("数组中有此数");
break;
}else {
number = false;
}
}
if (!number) {
System.out.println("数组中无此数");
System.exit(0);
}
}
}
删除元素
package com.base.day11;
public class Delbooks {
public static void main(String[] args) {
String[] books={"三国演义","红楼梦", "史记" , "西游记", "左传","菜根谭"};
for (int i = 0; i < books.length; i++) {
if ("左传".equals(books[i])){
for (int j = i;j < books.length - 1;j++){
books[j] = books[j + 1];
}
// break;
books[5] = null;
}
System.out.println(books[i]);
}
}
}