• 创建一个长度是5的数组,并填充随机数。使用for循环或者while循环,对这个数组实现反转效果


    package day01;
    
    import java.util.Random;
    
    /**
     * 首先创建一个长度是5的数组,并填充随机数。使用for循环或者while循环,对这个数组实现反转效果
     * @author Administrator
     *
     */
    public class Test16 {
    	public static void main(String[] args) {
    		int []a = new int[5];
    		for (int i = 1; i <= 100; i++) {
    			Random r =new Random();
    			a[0]=r.nextInt(i);
    			a[1]=r.nextInt(i);
    			a[2]=r.nextInt(i);
    			a[3]=r.nextInt(i);
    			a[4]=r.nextInt(i);
    		}
    		System.out.println("数组中的各个随机数是:");
            printArray(a);
            System.out.print("
    ");
            System.out.println("反转后的数是:");
            reverseArray1(a);
            printArray(a);
    		 
    	}
    	public static void printArray(int []a){
    		for (int i = 0; i < a.length; i++){
                System.out.print(a[i]+"	");
            }
    	}
    	public static void reverseArray1(int[] a){
            for(int i=0;i<a.length/2;i++){           //注意i不可以等于a.length
                swap(a,i,a.length-1-i);
            }
        }
        //交换方法----提高代码重用性
        public static void swap(int[] a,int x,int y){
            int temp=a[x];
            a[x]=a[y];
            a[y]=temp;
        }
    }
    

      

  • 相关阅读:
    List
    迭代器Iterator
    Collection方法
    Collection体系
    Date DateFormat SimpleDateFormat
    Calendar
    BigInteger & BigDecimal
    System类
    正则2 -- pattern和Matcher
    关于团队组成
  • 原文地址:https://www.cnblogs.com/TaoLeonis/p/6618543.html
Copyright © 2020-2023  润新知