输入10个数, 使其所有的数向后移m个位置

可借鉴,不可抄袭 来于CQUPT
问题描述:
从键盘输入10个整数,存放在一个数组中,然后使数组中的所有整数整体向后移动m个位置,最后m个数变成最前面的m个数,并输出移动后的结果。m从键盘输入。
输入形式:
输入10个整数,每个整数间用空格分隔,回车。然后输入整数m。
输出形式:
首先输出数组中的10个元素,然后输出后移m位以后的数组所有元素。
【输入输出样例】
Please input 10 numbers:
1 2 3 4 5 6 7 8 9 10
Your numbers are:
1 2 3 4 5 6 7 8 9 10
Please input m:
3
The new numbers are:
8 9 10 1 2 3 4 5 6 7

import java.util.Scanner;

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);
        System.out.println("Please input 10 numbers:");
        int[] num = new int[10];
        int m;
        for (int i = 0; i < num.length; i++) {
    
    
            num[i] = in.nextInt();
        }
        System.out.println("Your numbers are:");
        for (int i = 0; i < num.length; i++) {
    
    
            System.out.print(num[i]+" ");
        }
        System.out.println();
        System.out.println("Please input m:");
        m = in.nextInt();
        System.out.println("The new numbers are:");
        move(m,num);
        in.close();
    }

    public static void move(int m,int[] num){
    
    
        int[] n = new int[10];//用于储存需要后移的数字,作为存储位置。
        for (int i = 0; i < num.length; i++) {
    
    
            if (i+m<num.length){
    
    
                n[i+m] = num[i];

            }else {
    
    
                n[i+m-10] = num[i];
            }

        }
        for (int i = 0; i < n.length; i++) {
    
    //输出变换后的位置,由n存储的
            System.out.print(n[i]+" ");
        }
    }
}



猜你喜欢

转载自blog.csdn.net/qq_52050769/article/details/115581832