代码实现:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数

//有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
import java.util.ArrayList;
import java.util.Scanner;

public class Test36 {
	public static void main(String[] args) {
		int n = getN();
		int[] a = getNum(new int[n]);
		int m = getM(n);
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < a.length; i++) {
			list.add(a[i]);
		}
		for (int i = 0; i <= m; m--) {	
			list.add(list.get(i));
			list.remove(0);		
		}
		for (Integer integer : list) {
			System.out.print(integer+" ");
		}
	}

	public static int getM(int n) {
		int m = 0 ;
		while (true) {
			m = getN();
			if (m > n) {
				System.out.println("输入大于" + n + "请重新输入");
			}else{
				return m ;
			}
		}
	}

	public static int[] getNum(int[] a) {
		Scanner sc = new Scanner(System.in);
		String s = "";
		int i = 0;
		System.out.println("请输入第1个整数:");
		while (true) {
			s = sc.nextLine();
			try {
				int num = Integer.parseInt(s);
				a[i] = num;
				i++;
				if (i == a.length) {
					break;
				}
				System.out.println("请输入第" + (i + 1) + "个整数:");
			} catch (NumberFormatException e) {

				System.out.println("输入非法,请重新输入");
			}
		}
		return a;
	}

	public static int getN() {
		int n = 0;
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个数:");
		while (true) {
			String s = sc.nextLine();
			try {
				n = Integer.parseInt(s);
				break;
			} catch (NumberFormatException e) {
				System.out.println("输入错误,请重新输入:");
			}
		}
		return n;
	}
}

 

posted on 2017-03-09 20:04  LoaderMan  阅读(1675)  评论(0编辑  收藏  举报

导航