向数组中插入元素

数组中插入元素
/**
 * 
 */
package com.cn.learn.e4;

/**
 * @author 0
 *向数组中插入元素
 */
public class Insert4_5Num {
    public static void main(String[] args){
        int[] scores=new int[6];
        scores[0]=99;
        scores[1]=87;
        scores[2]=78;
        scores[3]=76;
        scores[4]=75;
        scores[5]=65;
        int insertat=0;
        int curr_score=77;
        for(int i=0;i<scores.length;i++){
            if(curr_score>scores[i]){
                insertat=i;//下标=3的时候,跳出循环,把下标的值赋给要插入的值的下标
                break;
            }
        }
        //原来位置元素向右挪一位
     //这个循环理解上有点难度,首先,i一定是i=scores.length-1,如果不减一,会数组越界
for(int i=scores.length-1;i>0;i--){ if(insertat==i){ break; } scores[i]=scores[i-1];//第1次把第5位的值赋给第6位上,依次累推,下标4的位值赋到下标5的位上,等到下标3的位的时候,就跳出循环,这样下标3的位是空出来了 }     //插入新成绩 scores[insertat]=curr_score;//上一步中第下标3的位空出来了,把77赋予给它

    //最后一个循环是打印新的数组元素出来
for(int i=0;i<scores.length;i++){ System.out.println(scores[i]); } } }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值