向数组中插入元素

/**
 * 
 */
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]); } } }
原文地址:https://www.cnblogs.com/sincoolvip/p/5434830.html