一维数组及应用

文章介绍了Java中数组的基础概念,包括数组的命名、元素类型、声明与赋值方法,以及动态从键盘录入信息、添加、修改和删除元素的示例。
摘要由CSDN通过智能技术生成

数组是一个变量,存储相同数据类型的一组数据

数组的基本要素:

标识符:数组的名称
数组元素:数组中存放的数据
元素下标:对数组元素进行编号,数组下标从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]);
        }
    }
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值