Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, November 08, 2012

C++, Java運算子優先權列表

C++
::	範圍解析	-
::	全域範圍解析	-
------      ------      ------
()	呼叫函數	左
[]	陣列標註	左
.	成員選擇	左
->	成員選擇(指標)	左
++	後置遞增	左
--	後置遞減	左
------      ------      ------
!	邏輯 NOT	右
~	位元補數	右
+	正		右
-	負		右
sizeof	型別大小	右
++	前置遞增	右
--	前置遞減	右
&	位址		右
*	間接參照	右
new	建立新物件	右
delete	刪除物件	右
------      ------      ------
()	成員(cast)	右
------      ------      ------
%	取餘數		左
*	乘		左
/	除		左
------      ------      ------
+	加		左
-	減		左
------      ------      ------
<<	位元左移	左
>>	位元右移	左
>	大於		左
>=	大於等於	左
<	小於		左
<=	小於等於	左
------      ------      ------
==	相等		左
!=	不等於		左
------      ------      ------
&	AND位元運算	左
------      ------      ------
|	OR位元運算	左
------      ------      ------
^	XOR位元運算	左
------      ------      ------
&&	邏輯AND		左
------      ------      ------
||	邏輯OR		左
------      ------      ------
?:	條件式		右
------      ------      ------
=	指定		右
------      ------      ------
,	逗號		左
------      ------      ------

Java
()	引數		左
[]	陣列存取	左
.	成員存取	左
++	後置遞增	左
--	後置遞減	左
------      ------      ------
!	邏輯 NOT	右
~	位元補數	右
+	正		右
-	負		右
++	前置遞增	右
--	前置遞減	右
------      ------      ------
new	建立新物件	右
()	強制轉型(cast)	右
------      ------      ------
%	取餘數		左
*	乘		左
/	除		左
------      ------      ------
+	加		左
-	減		左
------      ------      ------
<<	位元左移	左
>>	位元右移	左
>>>	無符號位元右移	左
------      ------      ------
>	大於		左
>=	大於等於	左
<	小於		左
<=	小於等於	左
instanceof	資料型態比較	左
------      ------      ------
==	相等		左
!=	不等於		左
------      ------      ------
&	AND位元運算	左
------      ------      ------
^	XOR位元運算	左
------      ------      ------
|	OR位元運算	左
------      ------      ------
&&	邏輯AND		左
------      ------      ------
||	邏輯OR		左
------      ------      ------
?:	條件式		右
------      ------      ------
=	指定		右
複合指定運算子		右
+= -= *= /= %=
&= |= ^= <<= >>= >>>=
------      ------      ------

Wednesday, October 03, 2012

Java範例程式 : package

將之前的車輛生產程式拆分成不同的 package.

程式碼
pCARb 目錄下 的 C13P315.java
package pCARb;
import pCAR2.Sub.*;

class C13P315
{
 public static void main(String[] args)
 {
  String querystr = "[[[查詢車輛資訊]]]";
  String setupstr = "[[[設定車輛資訊]]]";

  System.out.println("\n [[[ GM 汽車生產陣列 ]]]");
  Car[] GM = new Car[12];
  int BASEID = 6600;
  for(int i = 0; i < GM.length; i++){
   if( i < 6 ){
    GM[i] = new Car(i+BASEID, 1688.88888);
   } else if( i >= GM.length - 2 ){
    //GM[i] = new Car(i+6600, 0.0); //OK
    GM[i] = new Car(i+BASEID);
    //GM[i].setCar(i+6600);
   } else {
    GM[i] = new Car(i+BASEID, 1666.666);
   }
  }
  Car.showCarSum();

  System.out.println("\n [[[ GM ]]] " + setupstr);
  GM[2].setCar(1888.88);
  GM[0].setCar(1888.88);
  GM[8].setCar(1888.88);
  System.out.println("\n [[[ GM ]]] " + querystr);
  for(int i = 0; i < GM.length; i++){
   GM[i].showCar();
  }

  Car.showCarSum();

  System.out.println("\n\n打造第一台賽車");
  RacingCar rc1 = new RacingCar();
  rc1.setSpeed(600);
  rc1.setCar(666, 2500.0);
  rc1.showCar();
  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ LOTUS 汽車/賽車生產陣列 ]]]");
  RacingCar[] LOTUS = new RacingCar[6];
  BASEID = 8800;
  for(int i = 0; i < LOTUS.length; i++){
   if( i/3 == 0 ){
    ////LOTUS[i] = new RacingCar();
    ////LOTUS[i].setCar(i+BASEID, 2000.0);
    //LOTUS[i] = new RacingCar(i+BASEID, 2000.0);
    //LOTUS[i].setSpeed(500);
    LOTUS[i] = new RacingCar(i+BASEID, 2000.0, 500);
   } else {
    ////LOTUS[i] = new RacingCar();
    ////LOTUS[i].setCar(i+BASEID, 2500.0);
    //LOTUS[i] = new RacingCar(2500.0, i+BASEID);
    //LOTUS[i].setSpeed(660);
    LOTUS[i] = new RacingCar(2500.0, i+BASEID, 600);
   }
   System.out.print("調整渦輪加速級數 : ");
   LOTUS[i].setTurbo(i%3*2+1+i/3);
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ LOTUS ]]] " + querystr);
  for(int i = 0; i < LOTUS.length; i++){
   LOTUS[i].showCar();
  }

  Car.showCarSum();
  RacingCar.showCarSum();
 }
}

pCAR2/sub 目錄下的 Car.java 及 RacingCar.java
package pCAR2.Sub;

public class Car
{
 private int id;
 private double gasoline;
 private double MAXGAS = 2500;
 private static int carsum = 0;

 public Car()
 {
  id = 0;
  gasoline = 0.0;
  carsum++;
  this.manufactCar();
 }

 public Car(int id)
 {
  this();
  this.setCar(id);
 }

 public Car(int id, double gasoline)
 {
  this();
  this.setCar(id, gasoline);
 }

 public Car(double gasoline, int id)
 {
  this();
  this.setCar(gasoline, id);
 }

 private void prepareParts()
 {
  System.out.println("pCAR2 Sub");
  System.out.println("備料");
 }

 private void manufactCar()
 {
  this.prepareParts();
  System.out.println("製造一輛車");
 }

 public int getID()
 {
  return this.id;
 }

 public double getGas()
 {
  return this.gasoline;
 }

 public boolean setCar(int id)
 {
  if( id <= 0 ){
   System.out.println("!!! 車號 (" + id + ") 不可小於或等於 0. !!!");
   return false;
  } else {
   this.id = id;
   System.out.println("設定車號 " + this.id);
   return true;
  }
 }

 public boolean setCar(double gasoline)
 {
  if( gasoline < 0 || gasoline > this.MAXGAS ){
   System.out.println("!!! 油量 (" + gasoline + ") 不可小於 0 或大於 " + this.MAXGAS + ". !!!");
   return false;
  } else {
   this.gasoline = gasoline;
   System.out.println("車號 " + this.id + " 設定油量 " + this.gasoline);
   return true;
  }
 }

 public boolean setCar(int id, double gasoline)
 {
  return this.setCar(id) && this.setCar(gasoline);
 }

 public boolean setCar(double gasoline, int id)
 {
  return this.setCar(id) && this.setCar(gasoline);
 }

 public void showCar()
 {
  if( this.id == 0 ){
   System.out.print("車號 尚未設定");
  } else {
   System.out.print("車號 " + this.id);
  }

  if( this.gasoline <= 0 ){
   System.out.print(" ( 尚未設定油量 )\n");
  } else {
   System.out.print(" ( 油量 " + this.gasoline + " )\n");
  }
 }

 public static void showCarSum()
 {
  System.out.println("###### 總共生產 " + carsum + " 輛車. ######");
 }
}

package pCAR2.Sub;

public class RacingCar extends Car
{
 private int turbo = 1;
 private int speed;
 private static int carsum = 0;

 public RacingCar()
 {
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車");
 }

 public RacingCar(int id)
 {
  super(id);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.getID() + " 預設速度 " + speed + ")");
 }

 public RacingCar(int id, double gasoline)
 {
  super(id, gasoline);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.getID() + " 油量 " + this.getGas() + " 預設速度 " + speed + ")");
 }

 public RacingCar(double gasoline, int id)
 {
  super(gasoline, id);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.getID() + " 油量 " + this.getGas() + " 預設速度 " + speed + ")");
 }

 public RacingCar(int id, double gasoline, int speed)
 {
  super(id, gasoline);
  this.setSpeed(speed);
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.getID() + " 油量 " + this.getGas() + " 速度 " + this.speed + ")");
 }

 public RacingCar(double gasoline, int id, int speed)
 {
  super(gasoline, id);
  this.setSpeed(speed);
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.getID() + " 油量 " + this.getGas() + " 速度 " + this.speed + ")");
 }

 public void setSpeed(int speed)
 {
  int oldspeed = this.speed;
  if( oldspeed == speed ){
   System.out.println("賽車速度維持 " + this.speed);
  } else {
   this.speed = speed;
   System.out.println("將賽車速度由 " + oldspeed + " 調整為 " + this.speed);
  }
 }

 public void setTurbo(int turbo)
 {
  int oldturbo = this.turbo;
  if( oldturbo == turbo ){
   System.out.println("渦輪加速級數維持 " + this.turbo);
  } else {
   this.turbo = turbo;
   System.out.println("將渦輪加速級數由 " + oldturbo + " 調整為 " + this.turbo);
  }
 }

 public void showCar()
 {
  System.out.print("賽車");
  if( this.getID() == 0 ){
   System.out.print("車號 尚未設定");
  } else {
   System.out.print("車號 " + this.getID());
  }

  if( this.getGas() <= 0 ){
   System.out.print(" ( 尚未設定油量 ");
  } else {
   System.out.print(" ( 油量 " + this.getGas() + " ");
  }

  System.out.print("渦輪加速級數 " + this.turbo + " ");

  if( this.speed <= 0 ){
   System.out.print("尚未設定速度 )\n");
  } else {
   System.out.print("速度 " + this.speed + " )\n");
  }
 }

 public static void showCarSum()
 {
  System.out.println("###### 總共生產 " + carsum + " 輛賽車. ######");
 }
}

編譯及執行 script
#!/bin/bash

PATH=$PATH

PKGPATH="pCAR2/Sub"
PKGPATHb="pCARb"
SRC="C13P315.java"
CLASS="C13P315.class"
CarCLASS="Car.class"
RCarCLASS="RacingCar.class"

if [ ! -d $PKGPATH ];then
 echo "Package folder $PKGPATH does not existed."
 exit 1
fi

if [ ! -d $PKGPATHb ];then
 echo "Package folder $PKGPATHb does not existed."
 exit 1
fi

if [ -f ./$PKGPATHb/$SRC ]; then
 if [ ! -f ./$PKGPATHb/$CLASS ]||[ ! -f ./$PKGPATH/$CarCLASS ]||[ ! -f ./$PKGPATH/$RCarCLASS ]; then
  echo "Compile $SRC"
  javac $PKGPATHb/$SRC
 fi
fi

if [ -f ./$PKGPATHb/$CLASS ]&&[ -f ./$PKGPATH/$CarCLASS ]&&[ -f ./$PKGPATH/$RCarCLASS ]; then
 java pCARb.C13P315
else
 echo "Can not find $CLASS $CarCLASS $RCarCLASS"
fi

Java範例程式 : 界面的多重繼承

類別 Car 實現界面 iVehicle 及 iMaterial, 類別 Plane 實現界面 iVehicle 及 iMaterial.

程式碼
interface iVehicle
{
 void vShow();
}

interface iMaterial
{
 void mShow();
}

class Car implements iVehicle,iMaterial
{
 private int num;
 private double gas;

 public Car(int n, double g)
 {
  num = n;
  gas = g;
  System.out.println("生產了編號 " + num + " 油量 " + gas + " 的汽車");
 }

 public void vShow()
 {
  System.out.print("這是編號 " + num + " 油量 " + gas + " 的汽車");
 }

 public void mShow()
 {
  System.out.print("材質是鋼鐵");
 }

 public void move(){
  System.out.print("在路上奔跑");
 }

 public String toString()
 {
  return "這是編號 " + num + " 油量 " + gas + " 的汽車 材質是鋼鐵";
 }
}

class Plane implements iVehicle,iMaterial
{
 private int flight;

 public Plane(int f)
 {
  flight = f;
  System.out.println("生產了編號 " + flight + " 的飛機");
 }

 public void vShow()
 {
  System.out.print("這是編號 " + flight + " 的飛機");
 }

 public void mShow()
 {
  System.out.print("材料是鋁合金");
 }

 public void move()
 {
  System.out.print("在天空飛行");
 }

 public String toString()
 {
  return "這是編號 " + flight + " 的飛機 材料是鋁合金";
 }
}

class C12P297
{
 public static void main(String[] args)
 {
  Car[] icar = new Car[3];
  for(int i = 0; i < icar.length; i++){
   icar[i] = new Car(i+1, 2000.0);
  }

  Plane[] iplane = new Plane[3];
  for(int i = 0; i < iplane.length; i++){
   iplane[i] = new Plane(i+1);
  }

  System.out.println("\n查詢生產成果");
  for(int i = 0; i < icar.length; i++){
   System.out.print("序號 " + i + "  ");
   icar[i].vShow();
   icar[i].mShow();
   System.out.print(" 移動方式 ");
   icar[i].move();
   System.out.print("\n");
   System.out.println("\t" + icar[i]);
   System.out.println("\t### " + icar[i].getClass() + " ### ");
  }

  for(int i = 0; i < iplane.length; i++){
   System.out.print("序號 " + i + "  ");
   iplane[i].vShow();
   iplane[i].mShow();
   System.out.print(" 移動方式 ");
   iplane[i].move();
   System.out.print("\n");
   System.out.println("\t" + iplane[i]);
   System.out.println("\t### " + iplane[i].getClass() + " ### ");
  }
 }
}

Java範例程式 : 界面

以車(Car)及飛機(Plane)類別實作界面(iVehicle).

程式碼
interface iVehicle
{
 void show();
}

class Car implements iVehicle
{
 private int num;
 private double gas;

 public Car(int n, double g)
 {
  num = n;
  gas = g;
  System.out.println("生產了車號 " + num + " 油量 " + gas + " 的汽車");
 }

 public void show()
 {
  System.out.println("這是車號 " + num + " 油量 " + gas + " 的汽車");
 }
}

class Plane implements iVehicle
{
 private int flight;

 public Plane(int f)
 {
  flight = f;
  System.out.println("生產了編號 " + flight + " 的飛機");
 }

 public void show()
 {
  System.out.println("這是編號 " + flight + " 的飛機");
 }
}

class C12P293
{
 public static void main(String[] args)
 {
  iVehicle[] ivc;
  ivc = new iVehicle[3];

  ivc[0] = new Car(1, 2000.0);
  ivc[1] = new Plane(6);
  ivc[2] = new Plane(7);

  System.out.println("\n調查生產成果");
  for(int i = 0; i < ivc.length; i++){
   System.out.print("序號 " + i + " ");
   ivc[i].show();
  }
 }
}

Java範例程式 : 抽象類別

範例中將星球(Planet)作為抽象類別, 以太陽(Sun)及地球(Earth)類別繼承抽象類別.

程式碼
abstract class Planet
{
 protected double size;
 protected double expect_life;
 protected int speed;

 public void setSize(double s)
 {
  size = s;
  System.out.println("大小為 " + size);
 }

 public void setSpeed(int s)
 {
  speed = s;
  System.out.println("速度為 " + speed);
 }

 public void setLife(double elife)
 {
  expect_life = elife;
  System.out.println("預計壽命為 " + expect_life);
 }

 abstract void show();
}

class Sun extends Planet
{
 private double solarpower;
 private static int ssum = 0;

 Sun()
 {
  System.out.println("創造了一個太陽");
  ssum++;
  super.setSize(6000.0*(Math.random() * 77));
  super.setSpeed(3600*(int)(Math.random() * 77));
  super.setLife(500000.0*(Math.random() * 77));
 }

 Sun(double spower)
 {
  this();
  this.setPower(spower);
 }

 public void setPower(double spower)
 {
  solarpower = spower;
  System.out.println("點燃火力 " + solarpower + " 的太陽");
 }

 public void show()
 {
  System.out.println("這是一個太陽 ( 火力 " + solarpower + " 大小 " + size + " 速度 " + speed + " 壽命 " + expect_life + " )");
 }

 public static void showSum()
 {
  System.out.println("共有 " + ssum + " 顆太陽");
 }
}

class Earth extends Planet
{
 private int creatures;
 private static int esum = 0;

 Earth()
 {
  System.out.println("創造一個地球");
  esum++;
  super.setSize(360.0*(Math.random() * 77));
  super.setSpeed(60*(int)(Math.random() * 77));
  super.setLife(6000.0*(Math.random() * 77));
 }

 Earth(int c)
 {
  this();
  this.setCreature(c);
 }

 public void setCreature(int c)
 {
  creatures = c;
  System.out.println("創造 " + creatures + " 種生命");
 }

 public void show()
 {
  System.out.println("這是一個有 " + creatures + " 種生命的地球( 大小 " + size + " 速度 " + speed + " 壽命 " + expect_life + " )");
 }

 public static void showSum()
 {
  System.out.println("共有 " + esum + " 顆地球");
 }
}

class C12P286
{
 public static void main(String[] args)
 {
  System.out.println("創世紀 : 星球篇");
  Planet[] P = new Planet[12];
  for(int i = 0; i < P.length; i++){
   if( i < 2 ){
    P[i] = new Sun((((double)(i+1)*(Math.random() * 10))*10000));
   } else {
    P[i] = new Earth(i*(int)(Math.random() * 77));
   }
  }

  System.out.println("\n創世紀報告");
  for(int i = 0; i < P.length; i++){
   System.out.print("星球 " + i + " ");
   if(P[i] instanceof Sun){ System.out.print("S "); }
   if(P[i] instanceof Earth){ System.out.print("E "); }
   P[i].show();
  }

  Sun.showSum();
  Earth.showSum();
 }
}

Java 範例程式 : 繼承

範例中示範車輛(Car)為父類別, 賽車(RacingCar)為子類別. 其中展示多載(overloading), 覆載(overriding), 類別常數, 類別函式.

程式碼
class Car
{
 protected int id;
 protected double gasoline;
 private double MAXGAS = 2500;
 private static int carsum = 0;

 public Car()
 {
  id = 0;
  gasoline = 0.0;
  carsum++;
  this.manufactCar();
 }

 public Car(int id)
 {
  this();
  this.setCar(id);
 }

 public Car(int id, double gasoline)
 {
  this();
  this.setCar(id, gasoline);
 }

 public Car(double gasoline, int id)
 {
  this();
  this.setCar(gasoline, id);
 }

 private void prepareParts()
 {
  System.out.println("備料");
 }

 private void manufactCar()
 {
  this.prepareParts();
  System.out.println("製造一輛車");
 }

 public int getID()
 {
  return this.id;
 }

 public double getGas()
 {
  return this.gasoline;
 }

 public boolean setCar(int id)
 {
  if( id <= 0 ){
   System.out.println("!!! 車號 (" + id + ") 不可小於或等於 0. !!!");
   return false;
  } else {
   this.id = id;
   System.out.println("設定車號 " + this.id);
   return true;
  }
 }

 public boolean setCar(double gasoline)
 {
  if( gasoline < 0 || gasoline > this.MAXGAS ){
   System.out.println("!!! 油量 (" + gasoline + ") 不可小於 0 或大於 " + this.MAXGAS + ". !!!");
   return false;
  } else {
   this.gasoline = gasoline;
   System.out.println("車號 " + this.id + " 設定油量 " + this.gasoline);
   return true;
  }
 }

 public boolean setCar(int id, double gasoline)
 {
  return this.setCar(id) && this.setCar(gasoline);
 }

 public boolean setCar(double gasoline, int id)
 {
  return this.setCar(id) && this.setCar(gasoline);
 }

 public void showCar()
 {
  if( this.id == 0 ){
   System.out.print("車號 尚未設定 ");
  } else {
   System.out.print("車號 " + this.id + " ");
  }

  if( this.gasoline <= 0 ){
   System.out.print("尚未設定油量\n");
  } else {
   System.out.print("油量 " + this.gasoline + "\n");
  }
 }

 public static void showCarSum()
 {
  System.out.println("###### 總共生產 " + carsum + " 輛車. ######");
 }

 public String toString()
 {
  String cardesc = "";
  if( this.id == 0 ){
   cardesc = "車號 尚未設定 ";
  } else {
   cardesc = "車號 " + this.id + " ";
  }

  if( this.gasoline <= 0 ){
   cardesc = cardesc + "尚未設定油量";
  } else {
   cardesc = cardesc + "油量 " + this.gasoline;
  }
  return cardesc;
 }
}

class RacingCar extends Car
{
 private int turbo = 1;
 private int speed;
 private static int carsum = 0;

 public RacingCar()
 {
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車");
 }

 public RacingCar(int id)
 {
  super(id);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 預設速度 " + speed + ")");
 }

 public RacingCar(int id, double gasoline)
 {
  super(id, gasoline);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 預設速度 " + speed + ")");
 }

 public RacingCar(double gasoline, int id)
 {
  super(gasoline, id);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 預設速度 " + speed + ")");
 }

 public RacingCar(int id, double gasoline, int speed)
 {
  super(id, gasoline);
  this.setSpeed(speed);
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 速度 " + this.speed + ")");
 }

 public RacingCar(double gasoline, int id, int speed)
 {
  super(gasoline, id);
  this.setSpeed(speed);
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 速度 " + this.speed + ")");
 }

 public void setSpeed(int speed)
 {
  int oldspeed = this.speed;
  if( oldspeed == speed ){
   System.out.println("賽車速度維持 " + this.speed);
  } else {
   this.speed = speed;
   System.out.println("將賽車速度由 " + oldspeed + " 調整為 " + this.speed);
  }
 }

 public void setTurbo(int turbo)
 {
  int oldturbo = this.turbo;
  if( oldturbo == turbo ){
   System.out.println("渦輪加速級數維持 " + this.turbo);
  } else {
   this.turbo = turbo;
   System.out.println("將渦輪加速級數由 " + oldturbo + " 調整為 " + this.turbo);
  }
 }

 public void showCar()
 {
  System.out.print("賽車");
  super.showCar();
  System.out.print(" 渦輪加速級數 " + this.turbo + " ");

  if( this.speed <= 0 ){
   System.out.print("尚未設定速度\n");
  } else {
   System.out.print("速度 " + this.speed + "\n");
  }
 }

 public static void showCarSum()
 {
  System.out.println("###### 總共生產 " + carsum + " 輛賽車. ######");
 }

 public String toString()
 {
  String cardesc = "";
  cardesc = "賽車";
  cardesc = cardesc + super.toString();
  cardesc = cardesc + " 渦輪加速級數 " + this.turbo + " ";

  if( this.speed <= 0 ){
   cardesc = cardesc + "尚未設定速度";
  } else {
   cardesc = cardesc + "速度 " + this.speed;
  }
  return cardesc;
 }
}

class C11P276
{
 public static void main(String[] args)
 {
  String querystr = "[[[查詢車輛資訊]]]";
  String setupstr = "[[[設定車輛資訊]]]";

  System.out.println("\n [[[ GM 汽車生產陣列 ]]]");
  Car[] GM = new Car[12];
  int BASEID = 6600;
  for(int i = 0; i < GM.length; i++){
   if( i < 6 ){
    GM[i] = new Car(i+BASEID, 1688.88888);
   } else if( i >= GM.length - 2 ){
    //GM[i] = new Car(i+6600, 0.0); //OK
    GM[i] = new Car(i+BASEID);
    //GM[i].setCar(i+6600);
   } else {
    GM[i] = new Car(i+BASEID, 1666.666);
   }
  }
  Car.showCarSum();

  System.out.println("\n [[[ GM ]]] " + setupstr);
  GM[2].setCar(1888.88);
  GM[0].setCar(1888.88);
  GM[8].setCar(1888.88);
  System.out.println("\n [[[ GM ]]] " + querystr);
  for(int i = 0; i < GM.length; i++){
   GM[i].showCar();
  }

  Car.showCarSum();

  System.out.println("\n\n打造第一台賽車");
  RacingCar rc1 = new RacingCar();
  rc1.setSpeed(600);
  rc1.setCar(666, 2500.0);
  rc1.showCar();
  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ LOTUS 賽車生產陣列 ]]]");
  RacingCar[] LOTUS = new RacingCar[6];
  BASEID = 8800;
  for(int i = 0; i < LOTUS.length; i++){
   if( i/3 == 0 ){
    ////LOTUS[i] = new RacingCar();
    ////LOTUS[i].setCar(i+BASEID, 2000.0);
    //LOTUS[i] = new RacingCar(i+BASEID, 2000.0);
    //LOTUS[i].setSpeed(500);
    LOTUS[i] = new RacingCar(i+BASEID, 2000.0, 500);
   } else {
    ////LOTUS[i] = new RacingCar();
    ////LOTUS[i].setCar(i+BASEID, 2500.0);
    //LOTUS[i] = new RacingCar(2500.0, i+BASEID);
    //LOTUS[i].setSpeed(660);
    LOTUS[i] = new RacingCar(2500.0, i+BASEID, 600);
   }
   System.out.print("調整渦輪加速級數 : ");
   LOTUS[i].setTurbo(i%3*2+1+i/3);
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ LOTUS ]]] " + querystr);
  for(int i = 0; i < LOTUS.length; i++){
   LOTUS[i].showCar();
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ Car type RacingCar ]]] ");
  Car dcar;
  dcar = new RacingCar();
  dcar.setCar(777, 1800.0);
  //dcar.setSpeed(360);
  System.out.println("\n [[[ Car type RacingCar ]]] " + querystr);
  dcar.showCar();

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ Car type RacingCar ]]] ");
  Car dcar1;
  dcar1 = new RacingCar(778, 1900.0, 660);
  System.out.println("\n [[[ Car type RacingCar ]]] " + querystr);
  dcar1.showCar();

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ MIT 房車/賽車生產陣列 ]]]");
  Car[] MIT = new Car[6];
  BASEID = 3600;
  for(int i = 0; i < LOTUS.length; i++){
   if( i/3 == 0 ){
    MIT[i] = new Car(i+BASEID, 1200.0);
   } else {
    MIT[i] = new RacingCar(i+BASEID, 2200.0, (500 + 30 * (i % 3)));
    // Compile error : P.267 Car type var. can not access sub-class function
    //System.out.print("調整渦輪加速級數 : ");
    //MIT[i].setTurbo(i%3*2+1+i/3);
   }
   System.out.println(" ### " + MIT[i].getClass() + " ### ");
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ MIT ]]] " + querystr);
  for(int i = 0; i < MIT.length; i++){
   //MIT[i].showCar();
   System.out.println(MIT[i]);
  }

  Car.showCarSum();
  RacingCar.showCarSum();
 }
}

Java 範例程式 : 數字統計

根據資料中的數字出現情形, 可以不同的觀察期數範圍觀察出現情形. 符號分析目前僅有分析前三次的統計值變化. 這隻程式主要是可以以梯度權重的方式將數字出現的情形進行加權.

程式碼
import java.io.*;

class NumberStat3
{
	public static void main(String[] args)
	{
		// Define data file name and statistical file name
		String DEFAULTDATAFN = "number-data.txt";
		String DATAFN = DEFAULTDATAFN;
		String STATFN = "number-stat.txt";
		String STATFN2 = "number-stat2.txt";
		String STATFN3 = "number-stat3.txt";
		String STATFN3p = "number-stat3p.txt";

		String FIRSTLINE = "";
		String READLINE = "";
		// Define data row number, main region count, special region count, max of main, max of special
		int ROW = 0, MAINNUM = 0, SPNUM = 0, MAINMAX = 0, SPMAX = 0;
		// Define read counter
		int ReadCount = 0;
		// Define line length
		int LineLen = 0;
		// Define read number
		int ReadNum = -1;
		// Define lookup line
		int LOOKUP = 15;
		//Define BASE lookup sum
		int BASE = 3;
		//Define row number which begin to show statistical data
		int BEGINROW = 0;
		//Define add string to statistical file name
		String STATFNADD = "";

		// Read data file
		if(args.length > 0){ DATAFN = args[0]; }
		try{
			// Buffered reader and read count
			BufferedReader br = new BufferedReader(new FileReader(DATAFN));
			FIRSTLINE = br.readLine();
			ReadCount++;
			// Split first line for setup array
			String[] LINE = FIRSTLINE.split(",");
			LineLen = FIRSTLINE.length();
			for(int i = 0; i < LINE.length; i++){
				if(i != 8){
					ReadNum = -1;
					ReadNum = Integer.parseInt(LINE[i]);
				}
				//For debug
				//System.out.print(LINE[i] + " " + ReadNum + " ");
				switch(i){
				case 0:	ROW = ReadNum; System.out.println("設定資料筆數 " + ROW);
					break;
				case 1:	MAINNUM = ReadNum; System.out.println("設定主要區號碼個數 " + MAINNUM);
					break;
				case 2:	SPNUM = ReadNum; System.out.println("設定特別區號碼個數 " + SPNUM);
					break;
				case 3:	MAINMAX = ReadNum; System.out.println("設定主要區最大數字 " + MAINMAX);
					break;
				case 4:	SPMAX = ReadNum; System.out.println("設定特別區最大數字 " + SPMAX);
					break;
				case 5:	LOOKUP = ReadNum; System.out.println("設定前後查看期數 ");
					break;
				case 6:	BASE = ReadNum; System.out.println("設定統計期數基底數 ");
					break;
				case 7: BEGINROW = ReadNum-1; System.out.println("設定從 " + (BEGINROW+1) + " 期開始顯示統計資料");
					break;
				case 8: STATFNADD = LINE[i]; System.out.println("設定附加檔名字串 " + STATFNADD);
					break;
				default:	System.out.println("超過數量的參數不予理會.");
				}
			}
			System.out.print("\n");

			System.out.print("初始化陣列 : 資料陣列 ");
			int[][] data = new int[ROW][MAINNUM+SPNUM];
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < MAINNUM+SPNUM; j++){
					data[i][j] = 0;
				}
				System.out.print(".");
			}
			System.out.print("\n");

			System.out.print("初始化陣列 : 統計陣列 ");
			int[][][] anabe = new int[ROW][LOOKUP][MAINMAX+1];
			int[][][] anaaf = new int[ROW][LOOKUP][MAINMAX+1];
			int[][][] anaspbe = new int[ROW][LOOKUP][SPMAX+1];
			int[][][] anaspaf = new int[ROW][LOOKUP][SPMAX+1];
			int[][] statMAINp3be = new int[ROW][MAINMAX+1];
			int[][] statMAINp3af = new int[ROW][MAINMAX+1];
			int[][] statSPp3be = new int[ROW][SPMAX+1];
			int[][] statSPp3af = new int[ROW][SPMAX+1];
			char[][] statMAINp3beS = new char[ROW][MAINMAX+1];
			char[][] statSPp3beS = new char[ROW][SPMAX+1];
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < LOOKUP; j++){
					for(int k = 0; k < MAINMAX+1; k++){
						anabe[i][j][k] = 0;
					}
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < LOOKUP; j++){
					for(int k = 0; k < MAINMAX+1; k++){
						anaaf[i][j][k] = 0;
					}
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < LOOKUP; j++){
					for(int k = 0; k < SPMAX+1; k++){
						anaspbe[i][j][k] = 0;
					}
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < LOOKUP; j++){
					for(int k = 0; k < SPMAX+1; k++){
						anaspaf[i][j][k] = 0;
					}
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < MAINMAX+1; j++){
					statMAINp3be[i][j] = 0;
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < MAINMAX+1; j++){
					statMAINp3af[i][j] = 0;
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < SPMAX+1; j++){
					statSPp3be[i][j] = 0;
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < SPMAX+1; j++){
					statSPp3af[i][j] = 0;
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < MAINMAX+1; j++){
					statMAINp3beS[i][j] = '*';
				}
				System.out.print(".");
			}
			for(int i = 0; i < ROW; i++){
                                for(int j = 0; j < SPMAX+1; j++){
                                        statSPp3beS[i][j] = '*';
                                }
				System.out.print(".");
                        }
			System.out.print("\n");

			System.out.print("讀入資料並統計 ");
			READLINE = br.readLine();
			ReadCount++;
			while(READLINE != null && ReadCount <= ROW+1){
				//System.out.println(READLINE);
				LINE = READLINE.split(",");

				for(int i = 0; i < LINE.length; i++){
					ReadNum = -1;
					ReadNum = Integer.parseInt(LINE[i]);
					//System.out.print(ReadNum + " ");
					data[ReadCount-2][i] = ReadNum;
				}
				System.out.print(".");

				READLINE = br.readLine();
				ReadCount++;
			}
			System.out.print("\n");

			//Close data file
			br.close();

			//For debug
			/*for(int i = 0; i < ROW; i++){
				for(int j = 0; j < MAINNUM+SPNUM; j++){
					System.out.print(data[i][j] + " ");
				}
				System.out.print("\n");
			}*/

			for(int i = 0; i < ROW; i++){
				for(int j = 0; j < MAINNUM+SPNUM; j++){
					for(int l = 0; l < LOOKUP; l++){
						if(j < MAINNUM+SPNUM-1){
							//Main forward lookup
							if( i-l-1 >=0 ){
								anaaf[i-l-1][l][data[i][j]]++;
								anaaf[i-l-1][l][0]++;
							}
							//Main backward lookup
							if( i+l+1 < ROW ){
								anabe[i+l+1][l][data[i][j]]++;
								anabe[i+l+1][l][0]++;
							}
						}else{
							//Special forward lookup
							if( i-l-1 >=0 ){
								anaspaf[i-l-1][l][data[i][j]]++;
								anaspaf[i-l-1][l][0]++;
							}
							//Special backward lookup
							if( i+l+1 < ROW ){
								anaspbe[i+l+1][l][data[i][j]]++;
								anaspbe[i+l+1][l][0]++;
							}
						}
					}
				}
			}


			System.out.println("顯示統計結果並輸出檔案 ");
			//Define seperate string
			String SPSTR = "------      ------      ------      ------      ------      ------";

				//
				// Part III AdvSummary
				//
			//Define if fix BEGINROW
			boolean BRstatus = false;

			try{
				if(STATFNADD != ""){ STATFN3 = "number-stat3-" + STATFNADD + ".txt"; }
				PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(STATFN3)));

				System.out.println("分析三 依數字加總次數觀察");
				pw.println("分析三 依數字加總次數觀察");
				//Define summary count
				int asum = 0;
				if(BEGINROW -3 >= 0){ BEGINROW-=3; BRstatus = true; }

				System.out.println("一 主要區");
				pw.println("一 主要區");
				System.out.println("(一) 前期出現次數");
				pw.println("(一) 前期出現次數");
				for(int i = 0; i < MAINMAX+1; i++){
					if(i == 0){
						System.out.print("Total\t");
						pw.print("Total\t");
					} else {
						System.out.printf("%3d",i);
						pw.printf("%3d",i);
					}
				}
				System.out.print("\n");
				pw.print("\n");
				for(int i = BEGINROW; i < ROW; i++){
					for(int k = 0, j = 0; k < MAINMAX+1; k++){
						if(k == 0){
							System.out.printf("%5d\t",i+1);
							pw.printf("%5d\t",i+1);
						} else if(k == data[i][j] && j < MAINNUM){
							System.out.printf("%3s","  +");
							pw.printf("%3s","  +");
							j++;
						} else {
							System.out.printf("%3s","   ");
							pw.printf("%3s","   ");
						}
					}
					System.out.print("\n");
					pw.print("\n");
					for(int j = 0; j < MAINMAX+1; j++){
						asum = 0;
						for(int r = 0; r < LOOKUP/BASE; r++){
							for(int l = 0; l < BASE*(r+1); l++){
								asum+=anabe[i][l][j];
							}
						}
						if(j == 0){
							System.out.printf("%5d\t",asum);
							pw.printf("%5d\t",asum);
						} else {
							System.out.printf("%3d",asum);
							pw.printf("%3d",asum);
						}
						statMAINp3be[i][j] = asum;
					}
					System.out.print("\n");
					pw.print("\n");
				}
				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.print("統計分析\n");
				pw.print("統計分析\n");
				int MAXSCORE = 100;
				int DISTSCORE = 10;
				int BASESCALE = -1;
				int[] statBingo = new int[MAXSCORE/DISTSCORE];
				int[] statBASE = new int[MAXSCORE/DISTSCORE];
				for(int i = 0; i < statBingo.length; i++){ statBingo[i] = 0; }
				for(int i = 0; i < statBASE.length; i++){ statBASE[i] = 0; }

				for(int i = BEGINROW; i < ROW; i++){
					for(int j = 0; j < MAINNUM; j++){
						if(i > 0){
							if(statMAINp3be[i-1][data[i][j]] >= MAXSCORE){
								statBingo[statBingo.length-1]++;
							} else {
								statBingo[statMAINp3be[i-1][data[i][j]]/DISTSCORE]++;
							}
						}
					}
				}
				for(int i = BEGINROW; i < ROW-1; i++){
					for(int j = 1; j < MAINMAX+1; j++){
						BASESCALE = statMAINp3be[i][j]/DISTSCORE;
						if(BASESCALE >= MAXSCORE/DISTSCORE){
							statBASE[statBASE.length-1]++;
						} else {
							statBASE[BASESCALE]++;
						}
					}
				}
				System.out.print("Range ");
				pw.print("Range ");
				for(int i = 0; i < statBingo.length; i++){
					System.out.printf(" %3d~%3d",i*DISTSCORE,(i+1)*DISTSCORE-1);
					pw.printf(" %3d~%3d",i*DISTSCORE,(i+1)*DISTSCORE-1);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Count ");
				pw.print("Count ");
				for(int i = 0; i < statBingo.length; i++){
					System.out.printf(" %3d/%3d",statBingo[i],statBASE[i]);
					pw.printf(" %3d/%3d",statBingo[i],statBASE[i]);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Prob  ");
				pw.print("Prob  ");
				for(int i = 0; i < statBingo.length; i++){
					if(statBASE[i] == 0){
						System.out.printf("     N/A");
						pw.printf("     N/A");
					} else {
						System.out.printf("   %.3f",(float)statBingo[i]/(float)statBASE[i]);
						pw.printf("   %.3f",(float)statBingo[i]/(float)statBASE[i]);
					}
				}

				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.println("(二) 後期出現次數");
				pw.println("(二) 後期出現次數");
				for(int i = 0; i < MAINMAX+1; i++){
					if(i == 0){
						System.out.print("Total\t");
						pw.print("Total\t");
					} else {
						System.out.printf("%3d",i);
						pw.printf("%3d",i);
					}
				}
				System.out.print("\n");
				pw.print("\n");
				for(int i = BEGINROW; i < ROW; i++){
					for(int k = 0, j = 0; k < MAINMAX+1; k++){
						if(k == 0){
							System.out.printf("%5d\t",i+1);
							pw.printf("%5d\t",i+1);
						} else if(k == data[i][j] && j < MAINNUM){
							System.out.printf("%3s","  +");
							pw.printf("%3s","  +");
							j++;
						} else {
							System.out.printf("%3s","   ");
							pw.printf("%3s","   ");
						}
					}
					System.out.print("\n");
					pw.print("\n");
					for(int j = 0; j < MAINMAX+1; j++){
						asum = 0;
						for(int r = 0; r < LOOKUP/BASE; r++){
							for(int l = 0; l < BASE*(r+1); l++){
								asum+=anaaf[i][l][j];
							}
						}
						if(j == 0){
							System.out.printf("%5d\t",asum);
							pw.printf("%5d\t",asum);
						} else {
							System.out.printf("%3d",asum);
							pw.printf("%3d",asum);
						}
						statMAINp3af[i][j] = asum;
					}
					System.out.print("\n");
					pw.print("\n");
				}
				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.println("二 特別區號碼");
				pw.println("二 特別區號碼");
				System.out.println("(一) 前期出現次數");
				pw.println("(一) 前期出現次數");
				for(int i = 0; i < SPMAX+1; i++){
					if(i == 0){
						System.out.print("Total\t");
						pw.print("Total\t");
					} else {
						System.out.printf("%3d",i);
						pw.printf("%3d",i);
					}
				}
				System.out.print("\n");
				pw.print("\n");
				for(int i = BEGINROW; i < ROW; i++){
					for(int k = 0, j = MAINNUM; k < SPMAX+1; k++){
						if(k == 0){
							System.out.printf("%5d\t",i+1);
							pw.printf("%5d\t",i+1);
						} else if(j < MAINNUM+SPNUM && k == data[i][j]){
							System.out.printf("%3s","  +");
							pw.printf("%3s","  +");
							j++;
						} else {
							System.out.printf("%3s","   ");
							pw.printf("%3s","   ");
						}
					}
					System.out.print("\n");
					pw.print("\n");
					for(int j = 0; j < SPMAX+1; j++){
						asum = 0;
						for(int r = 0; r < LOOKUP/BASE; r++){
							for(int l = 0; l < BASE*(r+1); l++){
								asum+=anaspbe[i][l][j];
							}
						}
						if(j == 0){
							System.out.printf("%5d\t",asum);
							pw.printf("%5d\t",asum);
						} else {
							System.out.printf("%3d",asum);
							pw.printf("%3d",asum);
						}
						statSPp3be[i][j] = asum;
					}
					System.out.print("\n");
					pw.print("\n");
				}
				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.print("統計分析\n");
				pw.print("統計分析\n");
				MAXSCORE = 100;
				DISTSCORE = 10;
				BASESCALE = -1;
				int[] statBingoSP = new int[MAXSCORE/DISTSCORE];
				int[] statBASESP = new int[MAXSCORE/DISTSCORE];
				for(int i = 0; i < statBingoSP.length; i++){ statBingoSP[i] = 0; }
				for(int i = 0; i < statBASESP.length; i++){ statBASESP[i] = 0; }

				for(int i = BEGINROW; i < ROW; i++){
					for(int j = MAINNUM; j < MAINNUM+SPNUM; j++){
						if(i > 0){
							if(statSPp3be[i-1][data[i][j]] >= MAXSCORE){
								statBingoSP[statBingoSP.length-1]++;
							} else {
								statBingoSP[statSPp3be[i-1][data[i][j]]/DISTSCORE]++;
							}
						}
					}
				}
				for(int i = BEGINROW; i < ROW-1; i++){
					for(int j = 1; j < SPMAX+1; j++){
						BASESCALE = statSPp3be[i][j]/DISTSCORE;
						if(BASESCALE >= MAXSCORE/DISTSCORE){
							statBASESP[statBASE.length-1]++;
						} else {
							statBASESP[BASESCALE]++;
						}
					}
				}
				System.out.print("Range ");
				pw.print("Range ");
				for(int i = 0; i < statBingoSP.length; i++){
					System.out.printf(" %3d~%3d",i*DISTSCORE,(i+1)*DISTSCORE-1);
					pw.printf(" %3d~%3d",i*DISTSCORE,(i+1)*DISTSCORE-1);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Count ");
				pw.print("Count ");
				for(int i = 0; i < statBingoSP.length; i++){
					System.out.printf(" %3d/%3d",statBingoSP[i],statBASESP[i]);
					pw.printf(" %3d/%3d",statBingoSP[i],statBASESP[i]);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Prob  ");
				pw.print("Prob  ");
				for(int i = 0; i < statBingoSP.length; i++){
					if(statBASESP[i] == 0){
						System.out.printf("     N/A");
						pw.printf("     N/A");
					} else {
						System.out.printf("    %.3f",(float)statBingoSP[i]/(float)statBASESP[i]);
						pw.printf("    %.3f",(float)statBingoSP[i]/(float)statBASESP[i]);
					}
				}

				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.println("(二) 後期出現次數");
				pw.println("(二) 後期出現次數");
				for(int i = 0; i < SPMAX+1; i++){
					if(i == 0){
						System.out.print("Total\t");
						pw.print("Total\t");
					} else {
						System.out.printf("%3d",i);
						pw.printf("%3d",i);
					}
				}
				System.out.print("\n");
				pw.print("\n");
				for(int i = BEGINROW; i < ROW; i++){
					for(int k = 0, j = MAINNUM; k < SPMAX+1; k++){
						if(k == 0){
							System.out.printf("%5d\t",i+1);
							pw.printf("%5d\t",i+1);
						} else if(j < MAINNUM+SPNUM && k == data[i][j]){
							System.out.printf("%3s","  +");
							pw.printf("%3s","  +");
							j++;
						} else {
							System.out.printf("%3s","   ");
							pw.printf("%3s","   ");
						}
					}
					System.out.print("\n");
					pw.print("\n");
					for(int j = 0; j < SPMAX+1; j++){
						asum = 0;
						for(int r = 0; r < LOOKUP/BASE; r++){
							for(int l = 0; l < BASE*(r+1); l++){
								asum+=anaspaf[i][l][j];
							}
						}
						if(j == 0){
							System.out.printf("%5d\t",asum);
							pw.printf("%5d\t",asum);
						} else {
							System.out.printf("%3d",asum);
							pw.printf("%3d",asum);
						}
						statSPp3af[i][j] = asum;
					}
					System.out.print("\n");
					pw.print("\n");
				}
				System.out.print("\n\n");
				pw.print("\n\n");

				//Close file
				pw.close();
			} catch(IOException e){
				System.out.println("無法開啟檔案 " + STATFN3);
				System.exit(1);
			}

				//
				// Part III plus : Trend
				//
			//Fix BEGINROW
			if(BRstatus){ BEGINROW+=3; }

			try{
				if(STATFNADD != ""){ STATFN3p = "number-stat3p-" + STATFNADD + ".txt"; }
				PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(STATFN3p)));

				System.out.println("分析三+ 趨勢分析");
				pw.println("分析三+ 趨勢分析");

				System.out.println("一 主要區");
				pw.println("一 主要區");
				System.out.println("(一) 前期出現次數");
				pw.println("(一) 前期出現次數");
				for(int i = 0; i < MAINMAX+1; i++){
					if(i == 0){
						System.out.print("Num  \t");
						pw.print("Num  \t");
					} else {
						System.out.printf("%3d",i);
						pw.printf("%3d",i);
					}
				}
				System.out.print("\n");
				pw.print("\n");
				for(int i = BEGINROW; i < ROW; i++){
					for(int k = 0, j = 0; k < MAINMAX+1; k++){
						if(k == 0){
							System.out.printf("%5d\t",i+1);
							pw.printf("%5d\t",i+1);
						} else if(k == data[i][j] && j < MAINNUM){
							System.out.printf("%3s","  +");
							pw.printf("%3s","  +");
							j++;
						} else {
							System.out.printf("%3s","   ");
							pw.printf("%3s","   ");
						}
					}
					System.out.print("\n");
					pw.print("\n");
					if(i >= 3){
						for(int j = 0; j < MAINMAX+1; j++){
							if( j == 0){
								System.out.printf("%5s\t","");
								pw.printf("%5s\t","");
							} else {
								if((statMAINp3be[i-3][j] > statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] > statMAINp3be[i-1][j])){
									System.out.printf("%3s","  -");
									pw.printf("%3s","  -");
									statMAINp3beS[i][j] = '-';
								} else if((statMAINp3be[i-3][j] < statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] < statMAINp3be[i-1][j])){
									System.out.printf("%3s","  +");
									pw.printf("%3s","  +");
									statMAINp3beS[i][j] = '+';
								} else if(((statMAINp3be[i-3][j] < statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] == statMAINp3be[i-1][j]))||((statMAINp3be[i-3][j] == statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] < statMAINp3be[i-1][j]))){
									System.out.printf("%3s","  !");
									pw.printf("%3s","  !");
									statMAINp3beS[i][j] = '!';
								} else if(((statMAINp3be[i-3][j] > statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] == statMAINp3be[i-1][j]))||((statMAINp3be[i-3][j] == statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] > statMAINp3be[i-1][j]))){
									System.out.printf("%3s","  _");
									pw.printf("%3s","  _");
									statMAINp3beS[i][j] = '_';
								} else if(((statMAINp3be[i-3][j] > statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] < statMAINp3be[i-1][j]))||((statMAINp3be[i-3][j] < statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] > statMAINp3be[i-1][j]))){
									System.out.printf("%3s","  <");
									pw.printf("%3s","  <");
									statMAINp3beS[i][j] = '<';
								} else if(((statMAINp3be[i-3][j] == statMAINp3be[i-2][j])&&(statMAINp3be[i-2][j] == statMAINp3be[i-1][j]))||((statMAINp3be[i-3][j] == 0)&&(statMAINp3be[i-2][j] == 0)&&(statMAINp3be[i-1][j] == 0))){
									System.out.printf("%3s","  ?");
									pw.printf("%3s","  ?");
									statMAINp3beS[i][j] = '?';
								} else {
									System.out.printf("%3s","   ");
									pw.printf("%3s","   ");
									statMAINp3beS[i][j] = ' ';
								}
							}
						}
					}
					System.out.print("\n");
					pw.print("\n");
				}

				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.print("統計分析\n");
				pw.print("統計分析\n");
				// '+' 0 '!' 1 '-' 2 '_' 3 '<' 4 '?' 5 ' ' 6
				char[] SYM = {'+', '!', '-', '_', '<', '?', ' ', 'U'};
				int[] statBingoSYM = new int[SYM.length];
				int[] statBASESYM = new int[SYM.length];
				for(int i = 0; i < statBingoSYM.length; i++){ statBingoSYM[i] = 0; }
				for(int i = 0; i < statBASESYM.length; i++){ statBASESYM[i] = 0; }

				int SYMID = 7;
				for(int i = BEGINROW; i < ROW; i++){
					for(int j = 0; j < MAINNUM; j++){
						SYMID = 7;
						if(i > 0){
							switch(statMAINp3beS[i-1][data[i][j]]){
							case '+':	SYMID = 0;
									break;
							case '!':	SYMID = 1;
									break;
							case '-':	SYMID = 2;
									break;
							case '_':	SYMID = 3;
									break;
							case '<':	SYMID = 4;
									break;
							case '?':	SYMID = 5;
									break;
							case ' ':	SYMID = 6;
									break;
							default:	SYMID = 7;
							}
							statBingoSYM[SYMID]++;
						}
					}
				}
				for(int i = BEGINROW; i < ROW-1; i++){
					for(int j = 1; j < MAINMAX+1; j++){
						switch(statMAINp3beS[i][j]){
						case '+':       SYMID = 0;
								break;
						case '!':       SYMID = 1;
								break;
						case '-':       SYMID = 2;
								break;
						case '_':       SYMID = 3;
								break;
						case '<':       SYMID = 4;
								break;
						case '?':       SYMID = 5;
								break;
						case ' ':       SYMID = 6;
								break;
						default:        SYMID = 7;
						}
						statBASESYM[SYMID]++;
					}
				}
				System.out.print("Symbol ");
				pw.print("Symbol ");
				for(int i = 0; i < SYM.length; i++){
					System.out.printf("      %c",SYM[i]);
					pw.printf("      %c",SYM[i]);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Count  ");
				pw.print("Count  ");
				for(int i = 0; i < SYM.length; i++){
					System.out.printf("%3d/%3d",statBingoSYM[i],statBASESYM[i]);
					pw.printf("%3d/%3d",statBingoSYM[i],statBASESYM[i]);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Prob   ");
				pw.print("Prob   ");
				for(int i = 0; i < SYM.length; i++){
					if(statBASESYM[i] == 0){
						System.out.printf("    N/A");
						pw.printf("    N/A");
					} else {
						System.out.printf("  %.3f",(float)statBingoSYM[i]/(float)statBASESYM[i]);
						pw.printf("  %.3f",(float)statBingoSYM[i]/(float)statBASESYM[i]);
					}
				}

				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.println("二 特別區號碼");
				pw.println("二 特別區號碼");
				System.out.println("(一) 前期出現次數");
				pw.println("(一) 前期出現次數");
				for(int i = 0; i < SPMAX+1; i++){
					if(i == 0){
						System.out.print("Num  \t");
						pw.print("Num  \t");
					} else {
						System.out.printf("%3d",i);
						pw.printf("%3d",i);
					}
				}
				System.out.print("\n");
				pw.print("\n");
				for(int i = BEGINROW; i < ROW; i++){
					for(int k = 0, j = MAINNUM; k < SPMAX+1; k++){
						if(k == 0){
							System.out.printf("%5d\t",i+1);
							pw.printf("%5d\t",i+1);
						} else if(j < MAINNUM+SPNUM && k == data[i][j]){
							System.out.printf("%3s","  +");
							pw.printf("%3s","  +");
							j++;
						} else {
							System.out.printf("%3s","   ");
							pw.printf("%3s","   ");
						}
					}
					System.out.print("\n");
					pw.print("\n");
					if( i > 3 ){
						for(int j = 0; j < SPMAX+1; j++){
							if( j == 0){
								System.out.printf("%5s\t","");
								pw.printf("%5s\t","");
							} else {
								if((statSPp3be[i-3][j] > statSPp3be[i-2][j])&&(statSPp3be[i-2][j] > statSPp3be[i-1][j])){
									System.out.printf("%3s","  -");
									pw.printf("%3s","  -");
									statSPp3beS[i][j] = '-';
								} else if((statSPp3be[i-3][j] < statSPp3be[i-2][j])&&(statSPp3be[i-2][j] < statSPp3be[i-1][j])){
									System.out.printf("%3s","  +");
									pw.printf("%3s","  +");
									statSPp3beS[i][j] = '+';
								} else if(((statSPp3be[i-3][j] < statSPp3be[i-2][j])&&(statSPp3be[i-2][j] == statSPp3be[i-1][j]))||((statSPp3be[i-3][j] == statSPp3be[i-2][j])&&(statSPp3be[i-2][j] < statSPp3be[i-1][j]))){
									System.out.printf("%3s","  !");
									pw.printf("%3s","  !");
									statSPp3beS[i][j] = '!';
								} else if(((statSPp3be[i-3][j] > statSPp3be[i-2][j])&&(statSPp3be[i-2][j] == statSPp3be[i-1][j]))||((statSPp3be[i-3][j] == statSPp3be[i-2][j])&&(statSPp3be[i-2][j] > statSPp3be[i-1][j]))){
									System.out.printf("%3s","  _");
									pw.printf("%3s","  _");
									statSPp3beS[i][j] = '_';
								} else if(((statSPp3be[i-3][j] > statSPp3be[i-2][j])&&(statSPp3be[i-2][j] < statSPp3be[i-1][j]))||((statSPp3be[i-3][j] < statSPp3be[i-2][j])&&(statSPp3be[i-2][j] > statSPp3be[i-1][j]))){
									System.out.printf("%3s","  <");
									pw.printf("%3s","  <");
									statSPp3beS[i][j] = '<';
								} else if(((statSPp3be[i-3][j] == statSPp3be[i-2][j])&&(statSPp3be[i-2][j] == statSPp3be[i-1][j]))||((statSPp3be[i-3][j] == 0)&&(statSPp3be[i-2][j] == 0)&&(statSPp3be[i-1][j] == 0))){
									System.out.printf("%3s","  ?");
									pw.printf("%3s","  ?");
									statSPp3beS[i][j] = '?';
								} else {
									System.out.printf("%3s","   ");
									pw.printf("%3s","   ");
									statSPp3beS[i][j] = ' ';
								}
							}
						}
					}
					System.out.print("\n");
					pw.print("\n");
				}
				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.print("統計分析\n");
				pw.print("統計分析\n");
				int[] statBingoSYMSP = new int[SYM.length];
				int[] statBASESYMSP = new int[SYM.length];
				for(int i = 0; i < statBingoSYMSP.length; i++){ statBingoSYMSP[i] = 0; }
				for(int i = 0; i < statBASESYMSP.length; i++){ statBASESYMSP[i] = 0; }

				for(int i = BEGINROW; i < ROW; i++){
					for(int j = MAINNUM; j < MAINNUM+SPNUM; j++){
						SYMID = 7;
						if(i > 0){
							switch(statSPp3beS[i-1][data[i][j]]){
							case '+':	SYMID = 0;
									break;
							case '!':	SYMID = 1;
									break;
							case '-':	SYMID = 2;
									break;
							case '_':	SYMID = 3;
									break;
							case '<':	SYMID = 4;
									break;
							case '?':	SYMID = 5;
									break;
							case ' ':	SYMID = 6;
									break;
							default:	SYMID = 7;
							}
							statBingoSYMSP[SYMID]++;
						}
					}
				}
				for(int i = BEGINROW; i < ROW-1; i++){
					for(int j = 1; j < SPMAX+1; j++){
						switch(statSPp3beS[i][j]){
						case '+':       SYMID = 0;
								break;
						case '!':       SYMID = 1;
								break;
						case '-':       SYMID = 2;
								break;
						case '_':       SYMID = 3;
								break;
						case '<':       SYMID = 4;
								break;
						case '?':       SYMID = 5;
								break;
						case ' ':       SYMID = 6;
								break;
						default:        SYMID = 7;
						}
						statBASESYMSP[SYMID]++;
					}
				}

				System.out.print("Symbol ");
				pw.print("Symbol ");
				for(int i = 0; i < SYM.length; i++){
					System.out.printf("      %c",SYM[i]);
					pw.printf("      %c",SYM[i]);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Count  ");
				pw.print("Count  ");
				for(int i = 0; i < SYM.length; i++){
					System.out.printf("%3d/%3d",statBingoSYMSP[i],statBASESYMSP[i]);
					pw.printf("%3d/%3d",statBingoSYMSP[i],statBASESYMSP[i]);
				}
				System.out.print("\n");
				pw.print("\n");
				System.out.print("Prob   ");
				pw.print("Prob   ");
				for(int i = 0; i < SYM.length; i++){
					if(statBASESYMSP[i] == 0){
						System.out.printf("    N/A");
						pw.printf("    N/A");
					} else {
						System.out.printf("  %.3f",(float)statBingoSYMSP[i]/(float)statBASESYMSP[i]);
						pw.printf("  %.3f",(float)statBingoSYMSP[i]/(float)statBASESYMSP[i]);
					}
				}

				System.out.print("\n\n");
				pw.print("\n\n");

				System.out.println("程式分析完畢.");

				//Close file
				pw.close();
			} catch(IOException e){
				System.out.println("無法開啟檔案 " + STATFN3p);
				System.exit(1);
			}
		} catch(IOException e){
			System.out.println("找不到資料來源檔案 " + DATAFN);
			System.out.println("使用預設檔名 " + DEFAULTDATAFN + "\t請使用 java NumberStat3");
			System.out.println("使用指定檔案 PATH/to/FN\t\t請使用 java NumberStat3 PATH/to/FN");
			System.exit(1);
		}

	}
}

資料檔格式
[[[ Setting ]]]
Row 1
ROW,MAINNUM,SPNUM,MAINMAX,SPMAX,LOOKUP,BASE,BEGINROW,STATFNADD
------------------------------- ++++++++++++++++++++++++++++++
Essential Parameter             Optional Parameter

   ROW		data row number = total row number - 1
   MAINNUM	Main area number
   SPNUM	Special area number
   MAINMAX	Max value of main area
   SPMAX	Max value of special area
   LOOKUP	default : 15 (rows)
   BASE		default : 3  (rows)
   BEGINROW	default : 0  (row number)
   STATFNADD 	default : empty

[[[ Data ]]]
Row 2
MainNum_1,MainNum_2,...,MainNum_MAINNUM,SPNum_1,...,SPNum_SPNUM
...
Row ROW+1
MainNum_1,MainNum_2,...,MainNum_MAINNUM,SPNum_1,...,SPNum_SPNUM

測試資料
12,6,1,38,8,12,2,10,20120928test
3,4,16,18,36,37,2
2,14,15,16,28,29,8
6,9,11,13,19,23,2
2,6,10,18,23,26,5
6,20,26,33,34,35,5
2,4,11,22,23,25,8
7,13,28,33,35,38,6
5,7,15,28,35,37,6
1,20,22,23,29,38,3
9,15,16,34,36,37,5
6,13,16,29,33,36,4
13,14,24,25,26,35,3

輸出的分析結果
number-stat3-20120928test.txt
分析三 依數字加總次數觀察
一 主要區
(一) 前期出現次數
Total	  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    7	                    +                 +                                            +              +     +        +
  180	  0 15  4 10  0 16  0  0  5  5 11  0  5  4  4  8  0  9  5  6  0  6 16  0  6 11  0  4  4  0  0  0  6  6  6  4  4  0
    8	              +     +                       +                                      +                    +     +   
  198	  0 15  3  9  0 14  6  0  4  5 10  0 10  4  4  7  0  8  4  5  0  6 15  0  6 10  0 10  4  0  0  0 11  5 11  3  3  6
    9	  +                                                        +     +  +                 +                          +
  216	  0 12  3  8  6 13 12  0  4  4  9  0 10  3  9  6  0  7  4  5  0  5 13  0  5  9  0 15  3  0  0  0 11  5 17  3  9  6
   10	                          +                 +  +                                                     +     +  +   
  228	  6 12  2  7  6 11 11  0  3  4  8  0  8  3  9  5  0  6  3 10  0 11 18  0  5  8  0 14  9  0  0  0  9  4 15  2  8 11
   11	                 +                    +        +                                      +           +        +      
  240	  6  9  2  6  5 10 10  0  9  3  7  0  8  2 13 10  0  5  3 10  0 10 16  0  4  7  0 12  8  0  0  0  9 10 14  8 13 11
   12	                                      +  +                             +  +  +                          +         
  246	  5  9  1  5  5 14  9  0  8  3  6  0 12  2 13 15  0  4  2  8  0  9 14  0  4  6  0 11 13  0  0  0 13  9 12 13 12  9


統計分析
Range    0~  9  10~ 19  20~ 29  30~ 39  40~ 49  50~ 59  60~ 69  70~ 79  80~ 89  90~ 99
Count   33/146   3/ 44   0/  0   0/  0   0/  0   0/  0   0/  0   0/  0   0/  0   0/  0
Prob     0.226   0.068     N/A     N/A     N/A     N/A     N/A     N/A     N/A     N/A

(二) 後期出現次數
Total	  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    7	                    +                 +                                            +              +     +        +
  156	  6  0  0  0  6  5  6  0  5  0  0  0  9  4 11 10  0  0  0  6  0  6  6  4  4  4  0  6 11  0  0  0  5  5 10 10 11  6
    8	              +     +                       +                                      +                    +     +   
  132	  6  0  0  0  0  5  0  0  6  0  0  0 10  5  6 11  0  0  0  6  0  6  6  5  5  5  0  0 11  0  0  0  5  6  5 11  6  6
    9	  +                                                        +     +  +                 +                          +
  102	  0  0  0  0  0  6  0  0  6  0  0  0 11  5  6 12  0  0  0  0  0  0  0  5  5  5  0  0  6  0  0  0  6  6  5 12  6  0
   10	                          +                 +  +                                                     +     +  +   
   72	  0  0  0  0  0  6  0  0  0  0  0  0 12  6  0  6  0  0  0  0  0  0  0  6  6  6  0  0  6  0  0  0  6  0  6  6  0  0
   11	                 +                    +        +                                      +           +        +      
   36	  0  0  0  0  0  0  0  0  0  0  0  0  6  6  0  0  0  0  0  0  0  0  0  6  6  6  0  0  0  0  0  0  0  0  6  0  0  0
   12	                                      +  +                             +  +  +                          +         
    0	  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0


二 特別區號碼
(一) 前期出現次數
Total	  1  2  3  4  5  6  7  8
    7	                 +      
   30	  0  9  0  0 11  0  0 10
    8	                 +      
   33	  0  7  0  0 10  6  0 10
    9	        +               
   36	  0  7  0  0  9 12  0  8
   10	              +         
   38	  0  5  6  0  8 11  0  8
   11	           +            
   40	  0  5  6  0 13 10  0  6
   12	        +               
   41	  0  3  5  6 12  9  0  6


統計分析
Range    0~  9  10~ 19  20~ 29  30~ 39  40~ 49  50~ 59  60~ 69  70~ 79  80~ 89  90~ 99
Count    6/ 32   0/  8   0/  0   0/  0   0/  0   0/  0   0/  0   0/  0   0/  0   0/  0
Prob      0.188    0.000     N/A     N/A     N/A     N/A     N/A     N/A     N/A     N/A

(二) 後期出現次數
Total	  1  2  3  4  5  6  7  8
    7	                 +      
   26	  0  0 10  5  5  6  0  0
    8	                 +      
   22	  0  0 11  5  6  0  0  0
    9	        +               
   17	  0  0  5  6  6  0  0  0
   10	              +         
   12	  0  0  6  6  0  0  0  0
   11	           +            
    6	  0  0  6  0  0  0  0  0
   12	        +               
    0	  0  0  0  0  0  0  0  0



number-stat3p-20120928test.txt
分析三+ 趨勢分析
一 主要區
(一) 前期出現次數
Num  	  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
   10	                          +                 +  +                                                     +     +  +   
     	  ?  _  _  -  !  -  +  ?  _  _  -  ?  !  _  !  -  ?  -  _  _  ?  _  -  ?  _  -  ?  +  _  ?  ?  ?  !  _  +  _  <  !
   11	                 +                    +        +                                      +           +        +      
     	  !  _  _  -  !  -  <  ?  _  _  -  ?  _  _  !  -  ?  -  _  !  ?  <  <  ?  _  -  ?  <  <  ?  ?  ?  _  _  <  _  <  !
   12	                                      +  +                             +  +  +                          +         
     	  !  _  _  -  _  -  -  ?  <  _  -  ?  _  _  !  <  ?  -  _  !  ?  <  <  ?  _  -  ?  -  <  ?  ?  ?  _  <  -  <  <  !


統計分析
Symbol       +      !      -      _      <      ?             U
Count    0/  3  2/ 10  3/ 13  5/ 23  1/  8  1/ 19  0/  0  6/  0
Prob     0.000  0.200  0.231  0.217  0.125  0.053    N/A    N/A

二 特別區號碼
(一) 前期出現次數
Num  	  1  2  3  4  5  6  7  8
   10	              +         
     	  ?  _  ?  ?  -  +  ?  _
   11	           +            
     	  ?  _  !  ?  -  <  ?  _
   12	        +               
     	  ?  _  !  ?  <  -  ?  _


統計分析
Symbol       +      !      -      _      <      ?             U
Count    0/  1  1/  1  0/  2  0/  4  0/  1  1/  7  0/  0  1/  0
Prob     0.000  1.000  0.000  0.000  0.000  0.143    N/A    N/A


Tuesday, September 25, 2012

Java範例 : 物件導向觀念 : 繼承, 多載, 覆載

範例程式碼中包含以下觀念 :
繼承 : RacingCar 繼承自 Car.
多載 : setCar()
覆載 : showCar()
類別變數 : carsum
類別函式 : showCarSum()

程式碼
class Car
{
 protected int id;
 protected double gasoline;
 private double MAXGAS = 2500;
 private static int carsum = 0;

 public Car()
 {
  id = 0;
  gasoline = 0.0;
  carsum++;
  this.manufactCar();
 }

 public Car(int id)
 {
  this();
  this.setCar(id);
 }

 public Car(int id, double gasoline)
 {
  this();
  this.setCar(id, gasoline);
 }

 public Car(double gasoline, int id)
 {
  this();
  this.setCar(gasoline, id);
 }

 private void prepareParts()
 {
  System.out.println("備料");
 }

 private void manufactCar()
 {
  this.prepareParts();
  System.out.println("製造一輛車");
 }

 public int getID()
 {
  return this.id;
 }

 public double getGas()
 {
  return this.gasoline;
 }

 public boolean setCar(int id)
 {
  if( id <= 0 ){
   System.out.println("!!! 車號 (" + id + ") 不可小於或等於 0. !!!");
   return false;
  } else {
   this.id = id;
   System.out.println("設定車號 " + this.id);
   return true;
  }
 }

 public boolean setCar(double gasoline)
 {
  if( gasoline < 0 || gasoline > this.MAXGAS ){
   System.out.println("!!! 油量 (" + gasoline + ") 不可小於 0 或大於 " + this.MAXGAS + ". !!!");
   return false;
  } else {
   this.gasoline = gasoline;
   System.out.println("車號 " + this.id + " 設定油量 " + this.gasoline);
   return true;
  }
 }

 public boolean setCar(int id, double gasoline)
 {
  return this.setCar(id) && this.setCar(gasoline);
 }

 public boolean setCar(double gasoline, int id)
 {
  return this.setCar(id) && this.setCar(gasoline);
 }

 public void showCar()
 {
  if( this.id == 0 ){
   System.out.print("車號 尚未設定 ");
  } else {
   System.out.print("車號 " + this.id + " ");
  }

  if( this.gasoline <= 0 ){
   System.out.print("尚未設定油量\n");
  } else {
   System.out.print("油量 " + this.gasoline + "\n");
  }
 }

 public static void showCarSum()
 {
  System.out.println("###### 總共生產 " + carsum + " 輛車. ######");
 }
}

class RacingCar extends Car
{
 private int turbo = 1;
 private int speed;
 private static int carsum = 0;

 public RacingCar()
 {
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車");
 }

 public RacingCar(int id)
 {
  super(id);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 預設速度 " + speed + ")");
 }

 public RacingCar(int id, double gasoline)
 {
  super(id, gasoline);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 預設速度 " + speed + ")");
 }

 public RacingCar(double gasoline, int id)
 {
  super(gasoline, id);
  speed = 300;
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 預設速度 " + speed + ")");
 }

 public RacingCar(int id, double gasoline, int speed)
 {
  super(id, gasoline);
  this.setSpeed(speed);
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 速度 " + this.speed + ")");
 }

 public RacingCar(double gasoline, int id, int speed)
 {
  super(gasoline, id);
  this.setSpeed(speed);
  carsum++;
  System.out.println("生產一輛賽車(編號 " + this.id + " 油量 " + this.gasoline + " 速度 " + this.speed + ")");
 }

 public void setSpeed(int speed)
 {
  int oldspeed = this.speed;
  if( oldspeed == speed ){
   System.out.println("賽車速度維持 " + this.speed);
  } else {
   this.speed = speed;
   System.out.println("將賽車速度由 " + oldspeed + " 調整為 " + this.speed);
  }
 }

 public void setTurbo(int turbo)
 {
  int oldturbo = this.turbo;
  if( oldturbo == turbo ){
   System.out.println("渦輪加速級數維持 " + this.turbo);
  } else {
   this.turbo = turbo;
   System.out.println("將渦輪加速級數由 " + oldturbo + " 調整為 " + this.turbo);
  }
 }

 public void showCar()
 {
  System.out.print("賽車");
  super.showCar();
  System.out.print(" 渦輪加速級數 " + this.turbo + " ");

  if( this.speed <= 0 ){
   System.out.print("尚未設定速度\n");
  } else {
   System.out.print("速度 " + this.speed + "\n");
  }
 }

 public static void showCarSum()
 {
  System.out.println("###### 總共生產 " + carsum + " 輛賽車. ######");
 }
}

class C11P271
{
 public static void main(String[] args)
 {
  String querystr = "[[[查詢車輛資訊]]]";
  String setupstr = "[[[設定車輛資訊]]]";

  System.out.println("\n [[[ GM 汽車生產陣列 ]]]");
  Car[] GM = new Car[12];
  int BASEID = 6600;
  for(int i = 0; i < GM.length; i++){
   if( i < 6 ){
    GM[i] = new Car(i+BASEID, 1688.88888);
   } else if( i >= GM.length - 2 ){
    //GM[i] = new Car(i+6600, 0.0); //OK
    GM[i] = new Car(i+BASEID);
    //GM[i].setCar(i+6600);
   } else {
    GM[i] = new Car(i+BASEID, 1666.666);
   }
  }
  Car.showCarSum();

  System.out.println("\n [[[ GM ]]] " + setupstr);
  GM[2].setCar(1888.88);
  GM[0].setCar(1888.88);
  GM[8].setCar(1888.88);
  System.out.println("\n [[[ GM ]]] " + querystr);
  for(int i = 0; i < GM.length; i++){
   GM[i].showCar();
  }

  Car.showCarSum();

  System.out.println("\n\n打造第一台賽車");
  RacingCar rc1 = new RacingCar();
  rc1.setSpeed(600);
  rc1.setCar(666, 2500.0);
  rc1.showCar();
  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ LOTUS 賽車生產陣列 ]]]");
  RacingCar[] LOTUS = new RacingCar[6];
  BASEID = 8800;
  for(int i = 0; i < LOTUS.length; i++){
   if( i/3 == 0 ){
    ////LOTUS[i] = new RacingCar();
    ////LOTUS[i].setCar(i+BASEID, 2000.0);
    //LOTUS[i] = new RacingCar(i+BASEID, 2000.0);
    //LOTUS[i].setSpeed(500);
    LOTUS[i] = new RacingCar(i+BASEID, 2000.0, 500);
   } else {
    ////LOTUS[i] = new RacingCar();
    ////LOTUS[i].setCar(i+BASEID, 2500.0);
    //LOTUS[i] = new RacingCar(2500.0, i+BASEID);
    //LOTUS[i].setSpeed(660);
    LOTUS[i] = new RacingCar(2500.0, i+BASEID, 600);
   }
   System.out.print("調整渦輪加速級數 : ");
   LOTUS[i].setTurbo(i%3*2+1+i/3);
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ LOTUS ]]] " + querystr);
  for(int i = 0; i < LOTUS.length; i++){
   LOTUS[i].showCar();
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ Car type RacingCar ]]] ");
  Car dcar;
  dcar = new RacingCar();
  dcar.setCar(777, 1800.0);
  //dcar.setSpeed(360);
  System.out.println("\n [[[ Car type RacingCar ]]] " + querystr);
  dcar.showCar();

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ Car type RacingCar ]]] ");
  Car dcar1;
  dcar1 = new RacingCar(778, 1900.0, 660);
  System.out.println("\n [[[ Car type RacingCar ]]] " + querystr);
  dcar1.showCar();

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ MIT 房車/賽車生產陣列 ]]]");
  Car[] MIT = new Car[6];
  BASEID = 3600;
  for(int i = 0; i < LOTUS.length; i++){
   if( i/3 == 0 ){
    MIT[i] = new Car(i+BASEID, 1200.0);
   } else {
    MIT[i] = new RacingCar(i+BASEID, 2200.0, 500);
    // Compile error : P.267 Car type var. can not access sub-class function
    //System.out.print("調整渦輪加速級數 : ");
    //MIT[i].setTurbo(i%3*2+1+i/3);
   }
  }

  Car.showCarSum();
  RacingCar.showCarSum();

  System.out.println("\n [[[ MIT ]]] " + querystr);
  for(int i = 0; i < MIT.length; i++){
   MIT[i].showCar();
  }

  Car.showCarSum();
  RacingCar.showCarSum();
 }
}


執行結果
 [[[ GM 汽車生產陣列 ]]]
備料
製造一輛車
設定車號 6600
車號 6600 設定油量 1688.88888
備料
製造一輛車
設定車號 6601
車號 6601 設定油量 1688.88888
備料
製造一輛車
設定車號 6602
車號 6602 設定油量 1688.88888
備料
製造一輛車
設定車號 6603
車號 6603 設定油量 1688.88888
備料
製造一輛車
設定車號 6604
車號 6604 設定油量 1688.88888
備料
製造一輛車
設定車號 6605
車號 6605 設定油量 1688.88888
備料
製造一輛車
設定車號 6606
車號 6606 設定油量 1666.666
備料
製造一輛車
設定車號 6607
車號 6607 設定油量 1666.666
備料
製造一輛車
設定車號 6608
車號 6608 設定油量 1666.666
備料
製造一輛車
設定車號 6609
車號 6609 設定油量 1666.666
備料
製造一輛車
設定車號 6610
備料
製造一輛車
設定車號 6611
###### 總共生產 12 輛車. ######
 [[[ GM ]]] [[[設定車輛資訊]]]
車號 6602 設定油量 1888.88
車號 6600 設定油量 1888.88
車號 6608 設定油量 1888.88

 [[[ GM ]]] [[[查詢車輛資訊]]]
車號 6600 油量 1888.88
車號 6601 油量 1688.88888
車號 6602 油量 1888.88
車號 6603 油量 1688.88888
車號 6604 油量 1688.88888
車號 6605 油量 1688.88888
車號 6606 油量 1666.666
車號 6607 油量 1666.666
車號 6608 油量 1888.88
車號 6609 油量 1666.666
車號 6610 尚未設定油量
車號 6611 尚未設定油量
###### 總共生產 12 輛車. ######


打造第一台賽車
備料
製造一輛車
生產一輛賽車
將賽車速度由 300 調整為 600
設定車號 666
車號 666 設定油量 2500.0
賽車車號 666 油量 2500.0
 渦輪加速級數 1 速度 600
###### 總共生產 13 輛車. ######
###### 總共生產 1 輛賽車. ######

 [[[ LOTUS 賽車生產陣列 ]]]
備料
製造一輛車
設定車號 8800
車號 8800 設定油量 2000.0
將賽車速度由 0 調整為 500
生產一輛賽車(編號 8800 油量 2000.0 速度 500)
調整渦輪加速級數 : 渦輪加速級數維持 1
備料
製造一輛車
設定車號 8801
車號 8801 設定油量 2000.0
將賽車速度由 0 調整為 500
生產一輛賽車(編號 8801 油量 2000.0 速度 500)
調整渦輪加速級數 : 將渦輪加速級數由 1 調整為 3
備料
製造一輛車
設定車號 8802
車號 8802 設定油量 2000.0
將賽車速度由 0 調整為 500
生產一輛賽車(編號 8802 油量 2000.0 速度 500)
調整渦輪加速級數 : 將渦輪加速級數由 1 調整為 5
備料
製造一輛車
設定車號 8803
車號 8803 設定油量 2500.0
將賽車速度由 0 調整為 600
生產一輛賽車(編號 8803 油量 2500.0 速度 600)
調整渦輪加速級數 : 將渦輪加速級數由 1 調整為 2
備料
製造一輛車
設定車號 8804
車號 8804 設定油量 2500.0
將賽車速度由 0 調整為 600
生產一輛賽車(編號 8804 油量 2500.0 速度 600)
調整渦輪加速級數 : 將渦輪加速級數由 1 調整為 4
備料
製造一輛車
設定車號 8805
車號 8805 設定油量 2500.0
將賽車速度由 0 調整為 600
生產一輛賽車(編號 8805 油量 2500.0 速度 600)
調整渦輪加速級數 : 將渦輪加速級數由 1 調整為 6
###### 總共生產 19 輛車. ######
###### 總共生產 7 輛賽車. ######

 [[[ LOTUS ]]] [[[查詢車輛資訊]]]
賽車車號 8800 油量 2000.0
 渦輪加速級數 1 速度 500
賽車車號 8801 油量 2000.0
 渦輪加速級數 3 速度 500
賽車車號 8802 油量 2000.0
 渦輪加速級數 5 速度 500
賽車車號 8803 油量 2500.0
 渦輪加速級數 2 速度 600
賽車車號 8804 油量 2500.0
 渦輪加速級數 4 速度 600
賽車車號 8805 油量 2500.0
 渦輪加速級數 6 速度 600
###### 總共生產 19 輛車. ######
###### 總共生產 7 輛賽車. ######

 [[[ Car type RacingCar ]]] 
備料
製造一輛車
生產一輛賽車
設定車號 777
車號 777 設定油量 1800.0

 [[[ Car type RacingCar ]]] [[[查詢車輛資訊]]]
賽車車號 777 油量 1800.0
 渦輪加速級數 1 速度 300
###### 總共生產 20 輛車. ######
###### 總共生產 8 輛賽車. ######

 [[[ Car type RacingCar ]]] 
備料
製造一輛車
設定車號 778
車號 778 設定油量 1900.0
將賽車速度由 0 調整為 660
生產一輛賽車(編號 778 油量 1900.0 速度 660)

 [[[ Car type RacingCar ]]] [[[查詢車輛資訊]]]
賽車車號 778 油量 1900.0
 渦輪加速級數 1 速度 660
###### 總共生產 21 輛車. ######
###### 總共生產 9 輛賽車. ######

 [[[ MIT 房車/賽車生產陣列 ]]]
備料
製造一輛車
設定車號 3600
車號 3600 設定油量 1200.0
備料
製造一輛車
設定車號 3601
車號 3601 設定油量 1200.0
備料
製造一輛車
設定車號 3602
車號 3602 設定油量 1200.0
備料
製造一輛車
設定車號 3603
車號 3603 設定油量 2200.0
將賽車速度由 0 調整為 500
生產一輛賽車(編號 3603 油量 2200.0 速度 500)
備料
製造一輛車
設定車號 3604
車號 3604 設定油量 2200.0
將賽車速度由 0 調整為 500
生產一輛賽車(編號 3604 油量 2200.0 速度 500)
備料
製造一輛車
設定車號 3605
車號 3605 設定油量 2200.0
將賽車速度由 0 調整為 500
生產一輛賽車(編號 3605 油量 2200.0 速度 500)
###### 總共生產 27 輛車. ######
###### 總共生產 12 輛賽車. ######

 [[[ MIT ]]] [[[查詢車輛資訊]]]
車號 3600 油量 1200.0
車號 3601 油量 1200.0
車號 3602 油量 1200.0
賽車車號 3603 油量 2200.0
 渦輪加速級數 1 速度 500
賽車車號 3604 油量 2200.0
 渦輪加速級數 1 速度 500
賽車車號 3605 油量 2200.0
 渦輪加速級數 1 速度 500
###### 總共生產 27 輛車. ######
###### 總共生產 12 輛賽車. ######

Friday, September 21, 2012

Java範例程式 : 氣泡排序學生成績

以下採用三種不同的氣泡排序將學生成績由高至低排好.
方法一 內層迴圈所指位置與外層迴圈比大小(都是由左至右比較)
程式碼
import java.io.*;

class C7P155
{
 public static void main(String[] args) throws IOException
 {
  int student_num = 0, maxgr = 0, mingr = 0, maxid = 0, minid = 0, sum = 0, ccount = 0, scount = 0;
  boolean status = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("學生成績分析程式 ");
  do{
   System.out.print("請輸入學生人數 ");
   try{
    student_num = Integer.parseInt(br.readLine());
    status = false;
   } catch ( NegativeArraySizeException e ){
    System.out.println("請輸入正整數的學生人數.");
    status = true;
   } catch ( NumberFormatException e ){
    System.out.println("請輸入學生人數.");
    status = true;
   }
  } while (status);

  int grade[] = new int[student_num];

  System.out.println("\n開始輸入學生成績");

  for(int i = 0; i < student_num; i++){
   status = false;
   do{
    System.out.print("學生 " + (i+1) + " 成績 ");
    try{
     grade[i] = Integer.parseInt(br.readLine());
     sum += grade[i];
     if( i == 0 ){
      maxgr = mingr = grade[i];
     }else{
      if(grade[i] > maxgr){
       maxgr = grade[i]; maxid = i;
      } else if(grade[i] < mingr){
       mingr = grade[i]; minid = i;
      }
     }
     status = false;
    } catch ( NumberFormatException e ){
     System.out.println("請輸入正整數的成績.");
     status = true;
    }
   } while (status);
  }

  System.out.println("\n開始輸出學生成績");
  for(int i = 0; i < grade.length; i++){
   System.out.println("學生 " + (i+1) + " 成績 " + grade[i]);
  }
  System.out.println("\n最高最低成績");
  System.out.println("最高成績 第 " + (maxid+1) + " 號學生成績" + grade[maxid]);
  System.out.println("最低成績 第 " + (minid+1) + " 號學生成績" + grade[minid]);

  System.out.println("\n平均成績 " + (float)sum/(float)grade.length);

  System.out.println("\n成績排行榜");
  // Generate student id array
  int stid[] = new int[grade.length];
  for(int i = 0; i < grade.length; i++){ stid[i] = i; }

  // Sort by grade via bubble sort
  System.out.print("成績排序中 ");
  for(int i = 0; i < (grade.length - 1); i++){
   for(int j = i+1; j < grade.length; j++){
    if(grade[j] > grade[i]){
     // swap
     int tmpgr = grade[j];
     int tmpid = stid[j];
     grade[j] = grade[i];
     stid[j] = stid[i];
     grade[i] = tmpgr;
     stid[i] = tmpid;
     scount++;
     System.out.print("s");
    } else {
     System.out.print(".");
    }
    ccount++;
   }
  }
  System.out.println("\nSwap / Total comparison : " + scount + " / " + ccount);

  System.out.println("\n成績排序結果");
  int rank = 1;
  for(int i = 0; i < grade.length; i++){
   if( i != 0 && grade[i] != grade[i-1] ){ rank++; }
   System.out.println("名次 " + (i+1) + " 第 " + (stid[i]+1) + " 號學生成績 " + grade[i]);
  }
 }
}

物件導向版
import java.io.*;

class Student
{
 int sid;
 int grade;

 public void setGrade(int sid, int grade)
 {
  this.sid = sid;
  this.grade = grade;
 }

 public int getGrade()
 {
  return this.grade;
 }

 public int getSid()
 {
  return this.sid;
 }
}

class C8P158
{
 public static void main(String[] args) throws IOException
 {
  int student_num = 0, maxgr = 0, mingr = 0, maxid = 0, minid = 0, sum = 0, ccount = 0, scount = 0;
  boolean status = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("學生成績分析程式 ");
  do{
   System.out.print("請輸入學生人數 ");
   try{
    student_num = Integer.parseInt(br.readLine());
    status = false;
   } catch ( NegativeArraySizeException e ){
    System.out.println("請輸入正整數的學生人數.");
    status = true;
   } catch ( NumberFormatException e ){
    System.out.println("請輸入學生人數.");
    status = true;
   }
  } while (status);

  Student grade[] = new Student[student_num];

  System.out.println("\n開始輸入學生成績");

  for(int i = 0; i < student_num; i++){
   status = false;
   int tmpgrade = 0;
   do{
    System.out.print("學生 " + (i+1) + " 成績 ");
    try{
     tmpgrade = Integer.parseInt(br.readLine());
     grade[i] = new Student();
     grade[i].setGrade( i + 1, tmpgrade );
     sum += grade[i].getGrade();
     if( i == 0 ){
      maxgr = mingr = grade[i].getGrade();
     }else{
      if(grade[i].getGrade() > maxgr){
       maxgr = grade[i].getGrade(); maxid = i;
      } else if(grade[i].getGrade() < mingr){
       mingr = grade[i].getGrade(); minid = i;
      }
     }
     status = false;
    } catch ( NumberFormatException e ){
     System.out.println("請輸入正整數的成績.");
     status = true;
    }
   } while (status);
  }

  System.out.println("\n開始輸出學生成績");
  for(int i = 0; i < grade.length; i++){
   System.out.println("學生 " + (grade[i].getSid()) + " 成績 " + grade[i].getGrade());
  }
  System.out.println("\n最高最低成績");
  System.out.println("最高成績 第 " + grade[maxid].getSid() + " 號學生成績" + grade[maxid].getGrade());
  System.out.println("最低成績 第 " + grade[minid].getSid() + " 號學生成績" + grade[minid].getGrade());

  System.out.println("\n平均成績 " + (float)sum/(float)grade.length);

  System.out.println("\n成績排行榜");
  // Sort by grade via bubble sort
  System.out.print("成績排序中 ");
  for(int i = 0; i < (grade.length - 1); i++){
   for(int j = i+1; j < grade.length; j++){
    if(grade[j].getGrade() > grade[i].getGrade()){
     // swap
     Student tmpgr = grade[j];
     grade[j] = grade[i];
     grade[i] = tmpgr;
     scount++;
     System.out.print("s");
    } else {
     System.out.print(".");
    }
    ccount++;
   }
  }
  System.out.println("\nSwap / Total comparison : " + scount + " / " + ccount);

  System.out.println("\n成績排序結果");
  int rank = 1;
  for(int i = 0; i < grade.length; i++){
   if( i != 0 && grade[i].getGrade() != grade[i-1].getGrade() ){ rank++; }
   System.out.println("名次 " + (rank) + " 第 " + grade[i].getSid() + " 號學生成績 " + grade[i].getGrade());
  }
 }
}
方法二 外層迴圈由右至左, 為限制內層迴圈比較的右邊界. 內層迴圈迴圈由左至右, 相近位置兩兩比較大小.
程式碼
import java.io.*;

class C7P155_1
{
 public static void main(String[] args) throws IOException
 {
  int student_num = 0, maxgr = 0, mingr = 0, maxid = 0, minid = 0, sum = 0, scount = 0, ccount = 0;
  boolean status = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("學生成績分析程式 ");
  do{
   System.out.print("請輸入學生人數 ");
   try{
    student_num = Integer.parseInt(br.readLine());
    status = false;
   } catch ( NegativeArraySizeException e ){
    System.out.println("請輸入正整數的學生人數.");
    status = true;
   } catch ( NumberFormatException e ){
    System.out.println("請輸入學生人數.");
    status = true;
   }
  } while (status);

  int grade[] = new int[student_num];

  System.out.println("\n開始輸入學生成績");

  for(int i = 0; i < student_num; i++){
   status = false;
   do{
    System.out.print("學生 " + (i+1) + " 成績 ");
    try{
     grade[i] = Integer.parseInt(br.readLine());
     sum += grade[i];
     if( i == 0 ){
      maxgr = mingr = grade[i];
     }else{
      if(grade[i] > maxgr){
       maxgr = grade[i]; maxid = i;
      } else if(grade[i] < mingr){
       mingr = grade[i]; minid = i;
      }
     }
     status = false;
    } catch ( NumberFormatException e ){
     System.out.println("請輸入正整數的成績.");
     status = true;
    }
   } while (status);
  }

  System.out.println("\n開始輸出學生成績");
  for(int i = 0; i < grade.length; i++){
   System.out.println("學生 " + (i+1) + " 成績 " + grade[i]);
  }
  System.out.println("\n最高最低成績");
  System.out.println("最高成績 第 " + (maxid+1) + " 號學生成績" + grade[maxid]);
  System.out.println("最低成績 第 " + (minid+1) + " 號學生成績" + grade[minid]);

  System.out.println("\n平均成績 " + (float)sum/(float)grade.length);

  System.out.println("\n成績排行榜");
  // Generate student id array
  int stid[] = new int[grade.length];
  for(int i = 0; i < grade.length; i++){ stid[i] = i; }

  // Sort by grade via bubble sort
  System.out.print("成績排序中 ");
  for(int i = grade.length - 1; i > 0; i--){
   for(int j = 0; j < i; j++){
    if(grade[j+1] > grade[j]){
     // swap
     int tmpgr = grade[j+1];
     int tmpid = stid[j+1];
     grade[j+1] = grade[j];
     stid[j+1] = stid[j];
     grade[j] = tmpgr;
     stid[j] = tmpid;
     scount++;
     System.out.print("s");
    } else {
     System.out.print(".");
    }
    ccount++;
   }
  }
  System.out.println("\nSwap / Total comparison : " + scount + " / " + ccount);

  System.out.println("\n成績排序結果");
  int rank = 1;
  for(int i = 0; i < grade.length; i++){
   if( i != 0 && grade[i] != grade[i-1] ){ rank++; }
   System.out.println("名次 " + (rank) + " 第 " + (stid[i]+1) + " 號學生成績 " + grade[i]);
  }
 }
}

物件導向版
import java.io.*;

class Student
{
 int sid;
 int grade;

 public void setGrade(int sid, int grade)
 {
  this.sid = sid;
  this.grade = grade;
 }

 public int getGrade()
 {
  return this.grade;
 }

 public int getSid()
 {
  return this.sid;
 }
}

class C8P158_1
{
 public static void main(String[] args) throws IOException
 {
  int student_num = 0, maxgr = 0, mingr = 0, maxid = 0, minid = 0, sum = 0, scount = 0, ccount = 0;
  boolean status = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("學生成績分析程式 ");
  do{
   System.out.print("請輸入學生人數 ");
   try{
    student_num = Integer.parseInt(br.readLine());
    status = false;
   } catch ( NegativeArraySizeException e ){
    System.out.println("請輸入正整數的學生人數.");
    status = true;
   } catch ( NumberFormatException e ){
    System.out.println("請輸入學生人數.");
    status = true;
   }
  } while (status);

  Student grade[] = new Student[student_num];

  System.out.println("\n開始輸入學生成績");

  for(int i = 0; i < student_num; i++){
   status = false;
   do{
    System.out.print("學生 " + (i+1) + " 成績 ");
    try{
     grade[i] = new Student();
     grade[i].setGrade( i + 1, Integer.parseInt(br.readLine()) );
     sum += grade[i].getGrade();
     if( i == 0 ){
      maxgr = mingr = grade[i].getGrade();
     }else{
      if(grade[i].getGrade() > maxgr){
       maxgr = grade[i].getGrade(); maxid = i;
      } else if(grade[i].getGrade() < mingr){
       mingr = grade[i].getGrade(); minid = i;
      }
     }
     status = false;
    } catch ( NumberFormatException e ){
     System.out.println("請輸入正整數的成績.");
     status = true;
    }
   } while (status);
  }

  System.out.println("\n開始輸出學生成績");
  for(int i = 0; i < grade.length; i++){
   System.out.println("學生 " + grade[i].getSid() + " 成績 " + grade[i].getGrade());
  }
  System.out.println("\n最高最低成績");
  System.out.println("最高成績 第 " + grade[maxid].getSid() + " 號學生成績" + grade[maxid].getGrade());
  System.out.println("最低成績 第 " + grade[minid].getSid() + " 號學生成績" + grade[minid].getGrade());

  System.out.println("\n平均成績 " + (float)sum/(float)grade.length);

  System.out.println("\n成績排行榜");

  // Sort by grade via bubble sort
  System.out.print("成績排序中 ");
  for(int i = grade.length - 1; i > 0; i--){
   for(int j = 0; j < i; j++){
    if(grade[j+1].getGrade() > grade[j].getGrade()){
     // swap
     Student tmpgr = grade[j+1];
     grade[j+1] = grade[j];
     grade[j] = tmpgr;
     scount++;
     System.out.print("s");
    } else {
     System.out.print(".");
    }
    ccount++;
   }
  }
  System.out.println("\nSwap / Total comparison : " + scount + " / " + ccount);

  System.out.println("\n成績排序結果");
  int rank = 1;
  for(int i = 0; i < grade.length; i++){
   if( i != 0 && grade[i].getGrade() != grade[i-1].getGrade() ){ rank++; }
   System.out.println("名次 " + (rank) + " 第 " + grade[i].getSid() + " 號學生成績 " + grade[i].getGrade());
  }
 }
}
方法三 方法二的進化版. 將最後交換位置設為 sentinel, 讓比較次數減少.
程式碼
import java.io.*;

class C7P155_2
{
 public static void main(String[] args) throws IOException
 {
  int student_num = 0, maxgr = 0, mingr = 0, maxid = 0, minid = 0, sum = 0, scount = 0, ccount = 0;
  boolean status = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("學生成績分析程式 ");
  do{
   System.out.print("請輸入學生人數 ");
   try{
    student_num = Integer.parseInt(br.readLine());
    status = false;
   } catch ( NegativeArraySizeException e ){
    System.out.println("請輸入正整數的學生人數.");
    status = true;
   } catch ( NumberFormatException e ){
    System.out.println("請輸入學生人數.");
    status = true;
   }
  } while (status);

  int grade[] = new int[student_num];

  System.out.println("\n開始輸入學生成績");

  for(int i = 0; i < student_num; i++){
   status = false;
   do{
    System.out.print("學生 " + (i+1) + " 成績 ");
    try{
     grade[i] = Integer.parseInt(br.readLine());
     sum += grade[i];
     if( i == 0 ){
      maxgr = mingr = grade[i];
     }else{
      if(grade[i] > maxgr){
       maxgr = grade[i]; maxid = i;
      } else if(grade[i] < mingr){
       mingr = grade[i]; minid = i;
      }
     }
     status = false;
    } catch ( NumberFormatException e ){
     System.out.println("請輸入正整數的成績.");
     status = true;
    }
   } while (status);
  }

  System.out.println("\n開始輸出學生成績");
  for(int i = 0; i < grade.length; i++){
   System.out.println("學生 " + (i+1) + " 成績 " + grade[i]);
  }
  System.out.println("\n最高最低成績");
  System.out.println("最高成績 第 " + (maxid+1) + " 號學生成績" + grade[maxid]);
  System.out.println("最低成績 第 " + (minid+1) + " 號學生成績" + grade[minid]);

  System.out.println("\n平均成績 " + (float)sum/(float)grade.length);

  System.out.println("\n成績排行榜");
  // Generate student id array
  int stid[] = new int[grade.length];
  for(int i = 0; i < grade.length; i++){ stid[i] = i; }

  // Sort by grade via bubble sort
  System.out.print("成績排序中 ");
  for(int i = grade.length - 1, lastj = grade.length - 1; i > 0; i--){
   // For debug
   // System.out.print("(" + i + ")[" + lastj + "]");
   boolean swapstatus = false;
   for(int j = 0; j < i; j++){
    if(grade[j+1] > grade[j]){
     // swap
     int tmpgr = grade[j+1];
     int tmpid = stid[j+1];
     grade[j+1] = grade[j];
     stid[j+1] = stid[j];
     grade[j] = tmpgr;
     stid[j] = tmpid;
     lastj = j;
     swapstatus = true;
     scount++;
     System.out.print("s");
    } else {
     System.out.print(".");
    }
    ccount++;
   }
   if(swapstatus){ i = lastj + 1; } else { break;}
  }
  System.out.println("\nSwap / Total comparison : " + scount + " / " + ccount);

  System.out.println("\n成績排序結果");
  int rank = 1;
  for(int i = 0; i < grade.length; i++){
   if( i != 0 && grade[i] != grade[i-1] ){ rank++; }
   System.out.println("名次 " + (rank) + " 第 " + (stid[i]+1) + " 號學生成績 " + grade[i]);
  }
 }
}

物件導向版
import java.io.*;

class Student
{
 int sid;
 int grade;

 public void setGrade(int sid, int grade)
 {
  this.sid = sid;
  this.grade = grade;
 }

 public int getGrade()
 {
  return this.grade;
 }

 public int getSid()
 {
  return this.sid;
 }
}

class C8P158_2
{
 public static void main(String[] args) throws IOException
 {
  int student_num = 0, maxgr = 0, mingr = 0, maxid = 0, minid = 0, sum = 0, scount = 0, ccount = 0;
  boolean status = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("學生成績分析程式 ");
  do{
   System.out.print("請輸入學生人數 ");
   try{
    student_num = Integer.parseInt(br.readLine());
    status = false;
   } catch ( NegativeArraySizeException e ){
    System.out.println("請輸入正整數的學生人數.");
    status = true;
   } catch ( NumberFormatException e ){
    System.out.println("請輸入學生人數.");
    status = true;
   }
  } while (status);

  Student grade[] = new Student[student_num];

  System.out.println("\n開始輸入學生成績");

  for(int i = 0; i < student_num; i++){
   status = false;
   do{
    System.out.print("學生 " + (i+1) + " 成績 ");
    try{
     grade[i] = new Student();
     grade[i].setGrade( i + 1, Integer.parseInt(br.readLine()) );
     sum += grade[i].getGrade();
     if( i == 0 ){
      maxgr = mingr = grade[i].getGrade();
     }else{
      if(grade[i].getGrade() > maxgr){
       maxgr = grade[i].getGrade(); maxid = i;
      } else if(grade[i].getGrade() < mingr){
       mingr = grade[i].getGrade(); minid = i;
      }
     }
     status = false;
    } catch ( NumberFormatException e ){
     System.out.println("請輸入正整數的成績.");
     status = true;
    }
   } while (status);
  }

  System.out.println("\n開始輸出學生成績");
  for(int i = 0; i < grade.length; i++){
   System.out.println("學生 " + grade[i].getSid() + " 成績 " + grade[i].getGrade());
  }
  System.out.println("\n最高最低成績");
  System.out.println("最高成績 第 " + grade[maxid].getSid() + " 號學生成績" + grade[maxid].getGrade());
  System.out.println("最低成績 第 " + grade[minid].getSid() + " 號學生成績" + grade[minid].getGrade());

  System.out.println("\n平均成績 " + (float)sum/(float)grade.length);

  System.out.println("\n成績排行榜");

  // Sort by grade via bubble sort
  System.out.print("成績排序中 ");
  for(int i = grade.length - 1, lastj = grade.length - 1; i > 0; i--){
   // For debug
   // System.out.print("(" + i + ")[" + lastj + "]");
   boolean swapstatus = false;
   for(int j = 0; j < i; j++){
    if(grade[j+1].getGrade() > grade[j].getGrade()){
     // swap
     Student tmpgr = grade[j+1];
     grade[j+1] = grade[j];
     grade[j] = tmpgr;
     lastj = j;
     swapstatus = true;
     scount++;
     System.out.print("s");
    } else {
     System.out.print(".");
    }
    ccount++;
   }
   if(swapstatus){ i = lastj + 1; } else { break;}
  }
  System.out.println("\nSwap / Total comparison : " + scount + " / " + ccount);

  System.out.println("\n成績排序結果");
  int rank = 1;
  for(int i = 0; i < grade.length; i++){
   if( i != 0 && grade[i].getGrade() != grade[i-1].getGrade() ){ rank++; }
   System.out.println("名次 " + (rank) + " 第 " + grade[i].getSid() + " 號學生成績 " + grade[i].getGrade());
  }
 }
}

測試範例 : 七位學生的成績
範例一 : 1 2 3 4 5 6 7
反轉表 
1 2 3 4 5 6 7
0 1 2 3 4 5 6

方法一 : 21/21.
方法二 : 21/21.
方法三 : 21/21.

範例二 : 7 6 5 4 3 2 1
反轉表 
1 2 3 4 5 6 7
0 0 0 0 0 0 0

方法一 : 0/21.
方法二 : 0/21.
方法三 : 0/6.

範例三 : 5 7 4 1 6 3 2
反轉表 
1 2 3 4 5 6 7
0 1 1 0 0 3 1

方法一 : 6/21.
方法二 : 6/21.
方法三 : 6/14.

範例四 : 1 6 7 4 5 2 3
反轉表 
1 2 3 4 5 6 7
0 1 2 1 2 1 2

方法一 : 9/21.
方法二 : 9/21.
方法三 : 9/15.