zoukankan      html  css  js  c++  java
  • 2017-11-13

    Program:

      将数组的前三个数向后移动三位,并将数组的最后三个数移动到数组前三位

    代码如下:

     1 /*
     2  * 求解:将数组的前三个数向后移动三位,并将数组的最后三个数移动到数组前三位
     3  * 
     4  * Date Written:2017-11-13
     5  * 
     6  * */
     7 
     8 package test;
     9 
    10  
    11 public class TestDemo {
    12     
    13     public static void main(String args[]) {
    14     
    15         int[] nums = {1,2,3,4,5,6,7,8,9};    //初始化数组
    16         int n = 3;                           //移动的前n位元素
    17         
    18         operate(nums,n);        //移动元素
    19         display(nums);          //打印
    20         
    21     }
    22     
    23     //移动元素
    24     public static void operate(int[] nums,int n) {
    25         
    26         int[] temp = new int[n];        //初始化数组,保存最后n位元素(n为移动的元素个数)
    27         
    28         //将最后n位元素保存到临时数组
    29         for( int i = 0; i < temp.length; i++ ) {
    30             
    31             temp[i] = nums[nums.length - n + i];
    32         }
    33         
    34         //从后向前移动元素
    35         for( int i = nums.length - 1; i >= 0; i-- ) {
    36             
    37             /*
    38              * 将最后n位元素之前的元素移向后移动
    39              * 当i等于3时,即i-3等于0 时,第一个元素移动结束
    40              * 整体移动结束,然后将临时数组temp中的n个元素,移动到
    41              * 前n位
    42              * */
    43             if( i > 2 ) {
    44                 
    45                 nums[i] = nums[i-n];
    46             }else {                
    47                 
    48                 nums[i] = temp[i];
    49             }
    50         }
    51     }
    52 
    53 
    54     public static void display(int[] nums) {
    55         
    56         for(int i = 0; i < nums.length; i++) {
    57             
    58             System.out.print( nums[i] + "  " );
    59         }
    60     }
    61 
    62 }
  • 相关阅读:
    Python作业本——第4章 列表
    Python作业本——第3章 函数
    Python作业本——前言
    Yandex企业邮箱申请教程
    如何看待HTTP/3
    图床合集
    Windows File Recovery
    在线检测你的密码是否被泄露
    mybatis的mapper文件内容回顾
    java中系统中的常量
  • 原文地址:https://www.cnblogs.com/caizhen/p/7828619.html
Copyright © 2011-2022 走看看