Java入門-數組

Java入門-第五節-數組

    一 數組

1.爲什麼定義數組?

2.數組的定義:

3.聲明數組:

 

實例化數組:

public class Ai{
	
	public static void main( String [] args){
		int []mathsArray;
		mathsArray = new int [4];
		}
}
public class Ai{
	
	public static void main( String [] args){
		int [][]mathsArray;
		mathsArray = new int [2][];
		mathsArray[0]= new int[2];
		mathsArray[1]= new int[30];
		}
}

 

 

 

public class Ai{
	
	public static void main( String [] args){
		int []mathsArray = new int []{1,2,30};
		}
}
		
public class Ai{
	
	public static void main( String [] args){
		int [][] mathsArray=new int [][]{{1,2,3,4,5,6},{7,8,9,10,11,12}};
		}
}

常犯的錯誤:

 

二.數組的操作

 

1. 遍歷數組數據

一維


 
public class Ai{

	public static void main(String [] args){
		int []newsArray=new int []{1,2,3,4,5,6,7,8,9};
		for(int news:newsArray){
			System.out.println(news);
		}
	}
}

 

二維

 

public class Ai{

	public static void main(String [] args){
		int [][] mathsArray=new int [][]{{1,2,3,4,5,6},{7,8,9,10,11,12}};
		for(int[] newsArray:mathsArray){
			for(int news:newsArray){
				System.out.println(news);
			}	
		}
	}
}

常見錯誤

    

值傳遞(passby value)是指在調用函數時將實際參數複製 一份傳遞到函數中,這樣在函數中如果對 參數 進行修改,將不會影響到實際參數。

引用傳遞(pass by reference)是指在調用函數時將實際參數的地址直接 傳遞到函數中,那麼在函數中對 參數 所進行的修改,將影響到實際參數。

三  冒泡排序

public class Bi{
	
	public static void main(String [] args){
		int [] mathsArray = new int []{88,99,25,44,12,5885};
		int s=mathsArray.length;
		for(int i=0;i<s;i++){
			int flag=0;
			for(int j=0;j<s-i-1;j++){
				if(mathsArray[j]>mathsArray[j+1]){
					flag=mathsArray[j];
					mathsArray[j]=mathsArray[j+1];
					mathsArray[j+1]=flag;
				}
			}
		}
		for(int maths:mathsArray){
			System.out.println(maths);
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章