Java筆記丨10-1 陣列示例
多邊形Polygon.java
摘自高等教育出版社《Java程式設計(許滿武 主編)》
class Polygon{
private Point[] vertices; //vertices域的型別為Point[]
//構造器
public Polygon(Point... vers){ //形參vers的型別為Point...(可變形參)
vertices=new Point[vers.length]; //確定陣列大小,
for(int i=0;i<vertices.length;i++)
vertices[i]=vers[i]; //每個元素都是null
}
//列印所有點,逐元迴圈
public void print(){
for(Point p:vertices)
System.out.println(p);
}
public int getEdgeNum(){
return vertices.length;
}
//...
public static void main(String[] args){
Polygon triangle=new Polygon(new Point(11,22),new Point(22,33),new Point(33,22));
System.out.println(triangle.getEdgeNum());
triangle.print();
}
}
計算整數陣列平均值Arraytest.java
class Arraytest{
static double average(int[] values){
if(values==null||values.length==0)//當第一個表示式為真,則不再判斷第二個
throw new IllegalArgumentException();
else{
double sum=0.0;
for(int v:values)
sum+=v;
return sum/values.length;
}
}
public static void main(String[] args){
int[] data={11,22,33,44};
System.out.println(average(data));
}
}