java例题_36 移动数组中数据位置(用到数组的合并操作)

 1 /*36 【程序 36 移动位置】 
 2 题目:有 n 个整数,使其前面各数顺序向后移 m 个位置,最后 m 个数变成最前面的 m 个数,比如输入数字
 3 为 1 2 3 4 5 6 7 8 9 0,m=4,则结果为 7 8 9 0 1 2 3 4 5 6  
 4 */
 5 
 6 /*分析
 7  * 1、初始化数组a,并从键盘获得值
 8  * 2、声明m,并从键盘或者m值是多少
 9  * 3、再创建一个m大的数组b,用于临时存放a中最后m个数
10  * 4、将a中剩下的数向后移动==========不需要移动,直接新建c数组,将b并在a前面存入c中====重点!!
11  * 5、将b中的数并入a中======数组合并方法
12  * ================================================= 
13 String[] dd = new String[aa.length + bb.length];
14 System.arraycopy(aa, 0, dd, 0, aa.length);
15 System.arraycopy(bb, 0, dd, aa.length, bb.length);
16  * ==================================================
17  * */
18 
19 
20 
21 package homework;
22 
23 import java.util.Scanner;
24 
25 public class _36 {
26 
27     public static void main(String[] args) {
28         //从键盘获得数组的长度n
29         System.out.print("请问将输入的数组的长度n为多少? \n n=");    //询问数组的长度,n=10
30         Scanner sc=new Scanner(System.in);                 
31         int n=sc.nextInt();                                //得到n
32         //初始化数组并从键盘获得数组的值
33         System.out.println("请输入数组值,并用空格间隔:");    //提示输入数组值 (1 2 3 4 5 6 7 8 9 0)
34         int[] a=new int[n];
35         for (int i = 0; i < a.length; i++) {
36             a[i]=sc.nextInt();                      //为数组逐个赋值
37         }
38         //从键盘获得m值
39         System.out.print("请问顺序后移多少? \n m=");    //询问m值,m=4
40         int m=sc.nextInt();
41         //创建一个m大的数组b[m]
42         int[] b=new int[m];
43         for (int i = 0; i < m; i++) {          //m次循环,转移a中的数据到b
44             b[i]=a[a.length-m+i];
45         }
46 //        //测试b中的值
47 //        for (int i = 0; i < b.length; i++) {
48 //            System.out.print(b[i]+" ");
49 //        }
50         //新建c数组,将b并在a前面存入c中
51         int[] c = new int[a.length];           //新建一个长度为a.lengh的数组c
52         System.arraycopy(b, 0, c, 0, b.length);      //将b入新数组c中
53         System.arraycopy(a, 0, c, b.length, a.length-b.length);//将a存入c中,且存在b数组后面
54         
55         for (int i = 0; i < c.length; i++) {
56         System.out.print(c[i]+" ");
57     }    
58     }
59 
60 }

猜你喜欢

转载自www.cnblogs.com/scwyqin/p/12319205.html