不明白一下代碼的 for (car car : carForRent) 為什么是 car car : carForRent
不明白一下代碼的? ? ? for?(car?car?:?carForRent) ? ?為什么是 car car : carForRent? ? ?
car?[?]?carForRent={new?passengerCar(1,"奧迪A4",500,4),new?passengerCar(2,"馬自達(dá)6",400,4),
??????????????????????????????????????????new?pickUp(3,"皮卡雪6",450,4,2),new?passengerCar(4,"?金龍?",800,20),
??????????????????????????????????????????new?trunk(5,"松花江",400,4),new?trunk(6,"依維柯",1000,20)};
????????????System.out.println("序號(hào)"+"\t"+"汽車(chē)名稱(chēng)"+"\t"+"租金"+"\t"+"\t"+"容量");
????????????
?//打印輸出可供租的汽車(chē)清單
????????????for?(car?car?:?carForRent)?{
????????????????//用instanceOf來(lái)測(cè)試左邊類(lèi)型的對(duì)象是否是右邊類(lèi)型的實(shí)例,返回值為Boolean
????????????????if(car?instanceof?passengerCar){
????????????????????//若它是客車(chē)類(lèi)型的實(shí)例,則打印出客車(chē)應(yīng)該有的屬性值,這里注意強(qiáng)轉(zhuǎn),否則不會(huì)出現(xiàn)
????????????????????//passengerCar類(lèi)的CarCapacity屬性
????????????????????System.out.println(car.getCarNumber()+"\t"+car.getCarName()+"\t"+car.getCarRentMoney()
??????????????????????????????????????????????????+"/天"+"\t"+"載人:"+((passengerCar)car).getCarCapacity()+"人");
?????????????????????
????????????????}
????????????????if(car?instanceof?pickUp){
????????????????????System.out.println(car.getCarNumber()+"\t"+car.getCarName()+"\t"+car.getCarRentMoney()
??????????????????????????????????????????????????+"/天"+"\t"+"載人:"+((pickUp)car).getCarCapacity()+"人"+"\t"
??????????????????????????????????????????????????+"載貨:"+((pickUp)car).getCarCarryCargo()+"噸");
????????????????}
????????????????if(car?instanceof?trunk){
????????????????????System.out.println(car.getCarNumber()+"\t"+car.getCarName()+"\t"+car.getCarRentMoney()
??????????????????????????????????????????????????+"/天"+"\t"+"載貨:"+((trunk)car).getCarCarryCargo()+"噸");
????????????????}
????????????}
2016-10-25
?for?(Car?car?:?carForRent)這是另一種形式的for循環(huán),叫foreach,也叫遍歷式循環(huán)
?語(yǔ)法是for(類(lèi)型 ?變量名 : 數(shù)組名),就是每次按順序循環(huán)的從數(shù)組中取值,以你自己定義的變量名car保存,也就是上面寫(xiě)到的第二個(gè)car,第一個(gè)Car代表的是這個(gè)變量是車(chē)這個(gè)類(lèi)型的,在car這個(gè)變量中實(shí)際上保存的是一個(gè)車(chē)類(lèi)型的對(duì)象,這個(gè)對(duì)象就有載貨量、載客量、名字、租金這些屬性,你就可以在這個(gè)循環(huán)的過(guò)程中每次取出一個(gè)對(duì)象來(lái)操作,打印或者取得你想要的屬性值,它實(shí)際上和一般的for循環(huán)
for(int i=0;i=carForRent.length;i++){
????if(carForRent[i] instanceof?passengerCar){
????????????????????//若它是客車(chē)類(lèi)型的實(shí)例,則打印出客車(chē)應(yīng)該有的屬性值,這里注意強(qiáng)轉(zhuǎn),否則不會(huì)出現(xiàn)
????????????????????//passengerCar類(lèi)的CarCapacity屬性
????????????????????System.out.println(carForRent[i].getCarNumber()+"\t"+carForRent[i].getCarName()+"\t"+
carForRent[i].getCarRentMoney()
??????????????????????????????????????????????????+"/天"+"\t"+"載人:"+((passengerCar)carForRent[i]).getCarCapacity()+"人");?
????????????????}
}實(shí)現(xiàn)的效果是一樣的。
2016-10-25
樓上正解