Java 数组 之 一维数组 删除 元素

本文介绍了一个简单的Java程序,用于从一维整数数组中删除指定索引处的元素。通过创建一个临时数组来存放除被删除元素外的所有元素,最后用临时数组替换原数组。

http://www.verejava.com/?id=16992656053526

/*
题目: 删除scores数组索引index位置的值
思路:
    1. 创建一个临时比scores 小1的临时数组tempArray
    2. 将index前面的数据复制到tempArray前面
    3. 将index后面的数组依次复制到 tempArray 后面
    4. 将tempArray地址指针引用赋值给 scores
    5. 打印输出scores
*/
import java.util.Scanner;
public class ArrayDelete
{
    public static void main(String[] args)
    {
        //一维数组的定义和初始化
        int[] scores={90,70,50,80,60,85};
        System.out.println("请输入要删除的索引index :");
        Scanner in=new Scanner(System.in);
        int index=in.nextInt();

        //1. 创建一个临时比scores 小1的临时数组tempArray
        int[] tempArray=new int[scores.length-1];
        //2. 将index前面的数据复制到tempArray前面
        //3. 将index后面的数组依次复制到 tempArray 后面
        for(int i=0;i<scores.length;i++)
        {
            if(i<index)
                tempArray[i]=scores[i];
            if(i>index)
                tempArray[i-1]=scores[i];
        }
        //4. 将tempArray地址指针引用赋值给 scores
        scores=tempArray;
        //5.打印输出scores
        for(int i=0;i<scores.length;i++)
        {
            System.out.print(scores[i]+",");
        }

    }
}

http://www.verejava.com/?id=16992656053526

转载于:https://www.cnblogs.com/verejava/p/9189757.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值