Java:向整形数组插入元素

原题:编写程序。向整形数组的指定位置插入元素,并输出插入前后数组的值。

参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package cn.puruidong.accp_14;

/**
 * @author PuRuidong
 *
 */
/*
 * 编写程序。向整形数组的指定位置插入元素,并输出插入前后数组的值。
 * 书本:306页
 */
import java.util.Scanner;
public class Fivenum {

    /**
     * @param args
     */
    private int num [] = new int[] {10,20,30,55,99};//原数组
    private int no [] = new int [num.length+1];//新数组
    private static Scanner sc = new Scanner (System.in);
    private static int index ;//录入想插入的位置
    private static int value ;//录入想插入的值
   
    public void show (int index ,int value){
        ////////////输出插入前的数组
        System.out.println("插入前的数组:");
        for (int i=0;i<num.length;i++){//输出插入前的数组
            System.out.print(num[i]+" ");
        }
        /////赋值数组
        for (int c=0;c<num.length;c++){
            no[c] = num[c];
        }
        System.out.println();
            System.out.println("请输入想插入的位置(0~4):");
            index = sc.nextInt(); //录入想插入的位置
            System.out.println("请输入想插入的数值:");
            value = sc.nextInt(); //录入想插入的值
       
        for (int j=no.length-1;j>index;j--){ ////元素后移
            no[j] = no[j-1];
        }
        no[index] = value; //将 value的值放在index位置
        System.out.println("插入后的数组:");
        /////输出插入后的数组
        for (int k=0;k<no.length;k++){
            System.out.print(no[k]+" ");
        }
    }
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    Fivenum center = new Fivenum ();
    center.show(index, value);

    }

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据