一、數組
1、特點:a、數據類型相同 b、按順序排列
2、聲明數組
(1)聲明一維數組:
//只能在聲明的時候賦值
第二種:double [] string = new double [] {99,89.0,93.0};
//可以先聲明再賦值
/*
* double [] scores;
* scores = {99,89.0,93.0};錯誤
* double [] string;
* string = new double [] {99,89.0,93.0};正確
* /
(2)聲明二維數組//區別同上
第一種:String[] [] strings =new String[] []{{"xiaohong","123"},
{"xiaoming","234"},{"xiaolin","345"}};
第二種:String[] [] sttrings ={{"xiaohong","123"},
{"xiaoming","234"},{"xiaolin","345"}};
3、指定長度
(1)、一維數組
double [] strring = new double[3];//指定長度
(2)、二維數組
4、加強循環
for (double i:string) {
System.out.println(i);
}//string爲數組名
*********************************
//遍歷二維數組加強循環
for(String [] abc:strings) {
for(String bcd:abc) {
System.out.println(bcd);
}
}
二、條件與循環
1、if條件分支語句
if(布爾表達式1){
//布爾表達式1爲true時執行的代碼
}else if(布爾表達式2){
//布爾表達式1爲false但是布爾表達式2爲true時執行的代碼
}else if(布爾表達式3){
//布爾表達式1和布爾表達式2爲false但是布爾表達式3爲true時執行的代碼
}else{
//布爾表達式1、布爾表達式2和布爾表達式3均爲false時執行的代碼
}
【注意:1、if分支語句中去掉括號,則對第一行代碼有效;2、else不能單獨使用。】
2、switch條件分支語句
switch ( 表達式 ) {
case 常量1 :{
當表達式的值等於整型常量1時執行的語句;
break;//當一種情況包含其他情況時
}
case 常量2 :{
當表達式的值等於整型常量2時執行的語句;
break;
}
......
default:{
當表達式的值不滿足任何一個case的值時,執行的語句;
}
}
3、for循環
for (int i = 0;i < 100 ;i++ ){
System.out.println("a");
}
4、while循環
while(布爾型循環條件){
循環代碼塊
}
do {
循環操作
} while ( 布爾型循環條件);
三、排序
1、冒泡排序
int [] numbers = {1,2,3,4,5};
for(int time=1;time<numbers.length;time++) {
for(int i=0;i<numbers.length-time;i++) {
if(numbers[i]>numbers[i+1]) {
numbers[i]=numbers[i]+numbers[i+1];
numbers[i+1]=numbers[i]-numbers[i+1];
}
}
}
for (int i : numbers) {
System.out.println(i);
}
2、插入排序
int [] num= {1,2,4,5,5,3};
int date = num[5];
for(int i=0;i<num.length-1;i++) {
if(num[i]>date) {
int f = i;
for(int j=num.length-1;j>i;j--) {
num[j]=num[j-1];
}
num[f]=date;
break;
}
}
for (int p : num) {
System.out.println(p);
}
3、值傳遞和地址傳遞
//地址傳遞
int [] nums = {1};
int [] bers = nums;
bers[0] = 0;
System.out.println(nums[0]);
//結果:0
//值傳遞
int [] num = {1};
int [] age = {num[0]};
age[0] = 2;
System.out.println(num[0]);
//結果:1