創建一個長度是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("\n");
        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]+"\t");
        }
	}
	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;
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM