代码实现:有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) 编辑 收藏 举报