顯示具有 物件導向 標籤的文章。 顯示所有文章
顯示具有 物件導向 標籤的文章。 顯示所有文章

2013年6月11日 星期二

二進位檔案

bio
binary.txt
  pH?腲I?毨 !D-
import java.io.*;

class bio{
 public static void main(String[] args) throws IOException
 {

  DataInputStream din= new DataInputStream (
   new BufferedInputStream(
    new FileInputStream("binary.txt")));
  long n1=din.readLong();
  int n2=din.readInt();
  double n3=din.readDouble();
  System.out.println(" n1: "+n1+" n2: "+n2+" n3: "+n3);
  din.close();
 }
}

tio
text.txt
12345678901234512345678903.141592653589793
import java.io.*;

class tio{
 public static void main(String[] args) throws IOException
 {

      FileReader fr1=new FileReader("text.txt"); 
  BufferedReader bfr1= new BufferedReader(fr1);
  String str;
  
  while ((str=bfr1.readLine())!=null) //  
  {
   long n1=Long.parseLong(str.substring(0,15));
   int n2=Integer.parseInt(str.substring(15,25));
   double n3=Double.parseDouble(str.substring(25));
   System.out.println(" n1: "+n1+" n2: "+n2+" n3: "+n3);
  }
  fr1.close();
 }
}

2013年6月4日 星期二

二進位檔案讀寫實作

bio0604將資料輸入到2進位檔案pdata.txt裡面
import java.io.*;

class bio0604{
 public static void main(String[] args) throws IOException
 {
  DataOutputStream dout= new DataOutputStream (
   new BufferedOutputStream(
    new FileOutputStream("pdata.txt")));   // set filename

  dout.writeChars("M00031");  // output id (String)
  dout.writeChar('M');                // output gender (char)
  dout.writeInt(85);                      // output score1 (int)
  dout.writeDouble(0.27);                    // output weight1 (double)
  dout.writeInt(76);                      // output score2 (int)
  dout.writeDouble(0.33);                    // output weight2 (double)
  dout.writeInt(81);                      // output score3 (int)
  dout.writeDouble(0.4);                    // output weight3 (double)


  dout.writeChars("M00037");  // output id (String)
  dout.writeChar('F');                // output gender (char)
  dout.writeInt(62);                      // output score1 (int)
  dout.writeDouble(0.27);                    // output weight1 (double)
  dout.writeInt(54);                      // output score2 (int)
  dout.writeDouble(0.33);                    // output weight2 (double)
  dout.writeInt(50);                      // output score3 (int)
  dout.writeDouble(0.4);                    // output weight3 (double)

  dout.flush();
  dout.close();
  





 }
}




bout0604從pdata.txt將2進位檔案解析並印出
import java.io.*;

class bout0604{
 public static void main(String[] args) throws IOException
 {
  DataInputStream din= new DataInputStream (
   new BufferedInputStream(
    new FileInputStream("pdata.txt")));   // set filename

  char[] in=new char[6];
  char gen,star;
  int sc1,sc2,sc3;
  double w1,w2,w3,fin;
  String ss;

  for(int i=0;i<6;i++) in[i]=din.readChar();  // output id (String)
  gen=din.readChar();                // output gender (char)
  sc1=din.readInt();                      // output score1 (int)
  w1=din.readDouble();                    // output weight1 (double)
  sc2=din.readInt();                      // output score2 (int)
  w2=din.readDouble();                    // output weight2 (double)
  sc3=din.readInt();                      // output score3 (int)
  w3=din.readDouble();                    // output weight3 (double)
  
  ss= new String(in);
  if(gen=='M') star='*';
  else star=' ';
  fin=(int)((sc1*w1+sc2*w2+sc3*w3)*100)/100.0;
  System.out.println(ss+star+" "+sc1+" "+sc2+" "+sc3+" "+fin);



  for(int i=0;i<6;i++) in[i]=din.readChar();  // output id (String)
  gen=din.readChar();                // output gender (char)
  sc1=din.readInt();                      // output score1 (int)
  w1=din.readDouble();                    // output weight1 (double)
  sc2=din.readInt();                      // output score2 (int)
  w2=din.readDouble();                    // output weight2 (double)
  sc3=din.readInt();                      // output score3 (int)
  w3=din.readDouble();                    // output weight3 (double)
  
  ss= new String(in);
  if(gen=='M') star='*';
  else star=' ';
  fin=(int)((sc1*w1+sc2*w2+sc3*w3)*100)/100.0;
  System.out.println(ss+star+" "+sc1+" "+sc2+" "+sc3+" "+fin);

  din.close();

 }
}




以上為兩比資料分為同時寫入pdata.txt以及同時讀出,以下合併成一個程式碼
import java.io.*;

class bfix0604{
 public static void main(String[] args) throws IOException
 {
  DataOutputStream dout= new DataOutputStream (
   new BufferedOutputStream(
    new FileOutputStream("pdata.txt")));   // set filename

  dout.writeChars("M00031");  // output id (String)
  dout.writeChar('M');                // output gender (char)
  dout.writeInt(85);                      // output score1 (int)
  dout.writeDouble(0.27);                    // output weight1 (double)
  dout.writeInt(76);                      // output score2 (int)
  dout.writeDouble(0.33);                    // output weight2 (double)
  dout.writeInt(81);                      // output score3 (int)
  dout.writeDouble(0.4);                    // output weight3 (double)


  dout.writeChars("M00037");  // output id (String)
  dout.writeChar('F');                // output gender (char)
  dout.writeInt(62);                      // output score1 (int)
  dout.writeDouble(0.27);                    // output weight1 (double)
  dout.writeInt(54);                      // output score2 (int)
  dout.writeDouble(0.33);                    // output weight2 (double)
  dout.writeInt(50);                      // output score3 (int)
  dout.writeDouble(0.4);                    // output weight3 (double)

  dout.flush();
  dout.close();
  

  DataInputStream din= new DataInputStream (
   new BufferedInputStream(
    new FileInputStream("pdata.txt")));   // set filename

  char[] in=new char[6];
  char gen,star;
  int sc1,sc2,sc3;
  double w1,w2,w3,fin;
  String ss;

  for(int i=0;i<6;i++) in[i]=din.readChar();  // output id (String)
  gen=din.readChar();                // output gender (char)
  sc1=din.readInt();                      // output score1 (int)
  w1=din.readDouble();                    // output weight1 (double)
  sc2=din.readInt();                      // output score2 (int)
  w2=din.readDouble();                    // output weight2 (double)
  sc3=din.readInt();                      // output score3 (int)
  w3=din.readDouble();                    // output weight3 (double)
  
  ss= new String(in);
  if(gen=='M') star='*';
  else star=' ';
  fin=(int)((sc1*w1+sc2*w2+sc3*w3)*100)/100.0;
  System.out.println(ss+star+" "+sc1+" "+sc2+" "+sc3+" "+fin);



  for(int i=0;i<6;i++) in[i]=din.readChar();  // output id (String)
  gen=din.readChar();                // output gender (char)
  sc1=din.readInt();                      // output score1 (int)
  w1=din.readDouble();                    // output weight1 (double)
  sc2=din.readInt();                      // output score2 (int)
  w2=din.readDouble();                    // output weight2 (double)
  sc3=din.readInt();                      // output score3 (int)
  w3=din.readDouble();                    // output weight3 (double)
  
  ss= new String(in);
  if(gen=='M') star='*';
  else star=' ';
  fin=(int)((sc1*w1+sc2*w2+sc3*w3)*100)/100.0;
  System.out.println(ss+star+" "+sc1+" "+sc2+" "+sc3+" "+fin);

  din.close();



 }
}


執行序Thread實例

題目使用多執行序一起執行在執行的時候印出現在時間,利用不同的開頭字串區別開來,只利用for迴圈i的記數來緩衝無限迴圈,當把記數次數調低而出現次數會變多。
import java.util.Date;

class TimerThread extends Thread{
 String s;
 TimerThread(String ss){
  s=ss;

 }

 public void run(){
  while(true){
   for(int i=0;i<1000000000;i++);
   Date now=new Date();
   System.out.println(s+" thread >>>" + now);
  }
 }
}

public class ex0604a2{
    public static void main(String[] argv){
 TimerThread Thread1=new TimerThread("+++++");
 Thread1.start();
 TimerThread Thread2=new TimerThread("-----");
 Thread2.start();
 TimerThread Thread3=new TimerThread("******");
 Thread3.start();
     
  while (true) {
   for(int i=0;i<500000000;i++);
   Date now=new Date();
   System.out.println(" main >>>" + now);
  }

 }
}

物件導向期末小考5/28


物件導向設計原理期末考(II)A                     102/5/28
1. class TLprice 繼承抽象類別 time 且實作介面 rating,用以計算電話通話費。
(a) abstract 類別 time 定義四個成員變數,及三個抽象方法:
public int hh=0,mm=0,ss=0,seconds=0;
toTime(String timeString);  // 將時間字串轉成整數,分別存入
                         // hh (時),mm (分),ss(秒) 三個整數變數中
toSeconds();       //  hh*3600+mm*60+ss  seconds
getSeconds();       //  傳回轉成秒數的時間
(b) 介面 rating定義兩個抽象方法:
callSec();     //  傳回通話秒數 (終話時間 - 始話時間)
callPrice(char type, int callSec);        // 傳回通話費用
(c) class TLprice繼承抽象類別 time 且實作介面 rating,且增加三個方法:
getCallNo();      // 傳回發話號碼
getCallType()     // 傳回通話類別
setLprice()       // 設定區域通話費(以秒計價)
setGprice()       // 設定長途通話費(以秒計價)
setMprice()       // 設定行動通話費(以秒計價)

每筆通話記錄存放格式說明:
(a) 發話號碼Calling No.:0~7 字元
(b) 通話類別Call Type:8~8 字元   //  L:區域通話, G:長途通話, M:行動通話
(c) 始話時間:9~14字元
(d) 終話時間:15~20字元
      (a)        (b)    (c)         (d)
25380000   L  110325  111007

2. 印出每筆通話記錄之 Calling No.  Call Type  Call Sec.  Call Price

參考答案
編譯java檔案TLprice之後執行class的 prob10528印出結果
[javac TLprice.java]   之後  [java  prob10528]
abstract  class time{
 public int hh=0,mm=0,ss=0,seconds=0;
 abstract void toTime(String timeString);
 abstract  void toSeconds();
 abstract  int getSeconds(); 
}

interface rating{
 abstract  int callSec();
 abstract  double callPrice(char type, int callSec);
}
public class TLprice extends time implements rating{
 String callRec;
  public double Lprice=0, Gprice=0, Mprice=0;

 TLprice(String ss){
  callRec=ss;
 }
 public void toTime(String tt){
  hh=Integer.parseInt(tt.substring(0,2));
  mm=Integer.parseInt(tt.substring(2,4));
  ss=Integer.parseInt(tt.substring(4));
 }
 public void toSeconds(){
  seconds=hh*3600+mm*60+ss;
 }
 public int getSeconds(){
  return seconds;
 }
 public String getCallNo(){
  return callRec.substring(0,8);
 }
 public String getCallType(){
  return callRec.substring(8);
 }
 public int callSec(){           //  (終話時間 - 始話時間)
  int sec1, sec2;
  toTime(callRec.substring(9,15));     //  始話時間
  toSeconds();
  sec1=getSeconds();
  toTime(callRec.substring(15));         //  終話時間
  toSeconds();
  sec2=getSeconds();
  return sec2-sec1;
 } 
 void setLprice(double pp){
  Lprice=pp;
 }
 void setGprice(double pp){
  Gprice=pp;
 }
 void setMprice(double pp){
  Mprice=pp;
 }
 public double callPrice(char locate, int p){
  switch(locate){
  case 'L':
   return Lprice*p;
  case 'G':
   return Gprice*p;
  case 'M':
   return Mprice*p;
  default:
   return 0.0;
  }
 }  

}

class prob10528{
        public static void main(String[] args){
 double upL=0.05, upG=0.1, upM=0.15;   // unit price of 3 call type

 String[] callRec={"25380000L110325111007","25380011G122503123710","25381100M145912151559",
     "25382222M151111151616","25383311L155555161616","25385566G162022163559",
     "25386116M163333164316","25387123G170000172310","25388412L145912151559"};

 System.out.println(" Calling No.\t Call Type \t Call Sec. \t Call Price");
 for(String ss:callRec){
  TLprice tl=new TLprice(ss);
  tl.setLprice(upL);
  tl.setGprice(upG);
  tl.setMprice(upM);
  System.out.println(" "+tl.getCallNo()+"\t  "+tl.getCallType()+"  \t"+tl.callSec()+"  \t"+
                                   tl.callPrice(ss.charAt(8), tl.callSec()));
 }  
        }
}



物件導向設計原理期末考(II)B                     102/5/28
1. 輸入兩班的成績資料檔: clsA.txt & clsB.txt
(a) clsA.txt 的存放格式:學號/性別/姓名/成績1/成績2/成績3/成績4
學期成績=成績1*0.15+成績2*0.25+成績3*0.3+成績4*0.3
性別M:男生,性別F:女生

(b) clsB.txt 的存放格式:學號(0~7) 性別(8~8)姓名(9~23)
成績1(24~26)成績2(27~29)成績3(30~32)成績4(33~35)
學期成績=成績1*0.15+成績2*0.25+成績3*0.3+成績4*0.3
性別M:男生,性別F:女生

(c) 先輸入clsA.txt,再輸入clsB.txt

* (可以 Skip step 2)  30%
2. 輸出前,先將「學期成績」及格的學生資料依成績由高至低順序排序。
輸出前,先將「學期成績」不及格的學生資料依成績由高至低順序排序。

3. 將「學期成績」及格的學生資料寫入 pass.txt 檔,
將「學期成績」不及格的學生資料寫入 fail.txt 檔,

輸出的格式為:學號(*)  姓名  成績1  成績2  成績3  成績4  學期成績
男生於學號後加上「*」,女生於學號後加上「 」

prob20528無排序
import java.io.*;

class prob20528{
 public static void main(String[] args) throws IOException
 {


      FileReader fr1=new FileReader("clsA.txt");     // input file1: clsA.txt ==> A班學生成績資料檔
  BufferedReader bfr1= new BufferedReader(fr1);

      FileReader fr2=new FileReader("clsB.txt");     // input file2: clsB.txt ==> B班學生成績資料檔
  BufferedReader bfr2= new BufferedReader(fr2);
 
 //
 //    將學號、姓名、成績1(15%), 成績2(25%), 成績3(30%), 成績4(30%)及學期成績輸出
        //
  FileWriter fw1 = new FileWriter("pass.txt");     // output file1:pass.txt 學期成績及格資料檔
  BufferedWriter bfw1 = new BufferedWriter(fw1);

  FileWriter fw2 = new FileWriter("fail.txt");     // output file2:fail.txt 學期成績不及格資料檔
  BufferedWriter bfw2 = new BufferedWriter(fw2);
        //
        //
  String name,id,str,gender,sc1,sc2,sc3,outstring="";
  int recno=0,isc1,isc2,isc3, isc4, pno=0, fno=0;
  double fin;
  char star='*';

  while ((str=bfr1.readLine())!=null) //    read a record from input file1
  {
   String[] token=str.split("[/]");
   id=token[0];
   gender=token[1];
   name=token[2];
   isc1=Integer.parseInt(token[3]);
   isc2=Integer.parseInt(token[4]);
   isc3=Integer.parseInt(token[5]);
   isc4=Integer.parseInt(token[6]);
   fin=finScore(isc1,isc2,isc3,isc4);
   if(gender.compareTo("M")==0) star='*';
   else star=' ';
   System.out.println(id+star+"  "+name+"  "+gender+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);

   if(fin >= 60){ 
    bfw1.write(id+star+"  "+name+"  "+gender+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);
    bfw1.newLine();
   }// output to pass.txt
   else{
    bfw2.write(id+star+"  "+name+"  "+gender+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);
    bfw2.newLine();
   }// output to fail.txt

  }
  while ((str=bfr2.readLine())!=null) //    read a record from input file2
  {
   id=str.substring(0,8);
   gender=str.substring(8,9);
   name=str.substring(9,24);
   isc1=Integer.parseInt(str.substring(24,27));
   isc2=Integer.parseInt(str.substring(27,30));
   isc3=Integer.parseInt(str.substring(30,33));
   isc4=Integer.parseInt(str.substring(33));
   fin=finScore(isc1,isc2,isc3,isc4);
   if(gender.compareTo("M")==0) star='*';
   else star=' ';

   System.out.println(id+star+"  "+name+"  "+gender+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);

   if(fin >= 60){ 
    bfw1.write(id+star+"  "+name+"  "+gender+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);
    bfw1.newLine();
   }// output to pass.txt
   else{
    bfw2.write(id+star+"  "+name+"  "+gender+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);
    bfw2.newLine();
   }// output to fail.txt
 
  }
  bfw1.flush();
  bfw2.flush();
  fr1.close();
  fw1.close();
  fr2.close();
  fw2.close();
 }
 static double finScore(int a, int b, int c, int d){
  return (int)((a*0.15+b*0.25+c*0.3+d*0.3)*100)/100.0;
 }
}


prob20528sort排序版本
import java.io.*;

class score{
 String[] data;
 int no;

 score(String[] ss, int num){
  data=ss;
  no=num;
 }
 void sort(){
  String tmp;
  for(int i=0;i<no-1;i++){
   for(int j=i+1;j<no;j++){
    if(data[i].compareTo(data[j]) < 0){
     tmp=data[i];
     data[i]=data[j];
     data[j]=tmp;
    }
   }
  }
 }
}


class prob20528sort{
 public static void main(String[] args) throws IOException
 {

      FileReader fr1=new FileReader("clsA.txt");     // input file1: clsA.txt ==> A班學生成績資料檔
  BufferedReader bfr1= new BufferedReader(fr1);

      FileReader fr2=new FileReader("clsB.txt");     // input file2: clsB.txt ==> B班學生成績資料檔
  BufferedReader bfr2= new BufferedReader(fr2);
 
 //
 //    將學號、姓名、成績1(15%), 成績2(25%), 成績3(30%), 成績4(30%)及學期成績輸出
        //
  FileWriter fw1 = new FileWriter("pass.txt");     // output file1:pass.txt 學期成績及格資料檔
  BufferedWriter bfw1 = new BufferedWriter(fw1);

  FileWriter fw2 = new FileWriter("fail.txt");     // output file2:fail.txt 學期成績不及格資料檔
  BufferedWriter bfw2 = new BufferedWriter(fw2);
        //
        //
  String name,id,str,gender,sc1,sc2,sc3,outstring="";
  int recno=0,isc1,isc2,isc3, isc4, pno=0, fno=0;
  double fin;
  String[] pass=new String[20];   // for sorting
  String[] fail=new String[20];   // for sorting
  char star='*';

  while ((str=bfr1.readLine())!=null) //    read a record from input file1
  {
   String[] token=str.split("[/]");
   id=token[0];
   gender=token[1];
   name=token[2];
   isc1=Integer.parseInt(token[3]);
   isc2=Integer.parseInt(token[4]);
   isc3=Integer.parseInt(token[5]);
   isc4=Integer.parseInt(token[6]);
   fin=finScore(isc1,isc2,isc3,isc4);
   if(gender.compareTo("M")==0) star='*';
   else star=' ';

   System.out.println(id+star+"  "+gender+" "+name+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);
   outstring=fin+","+id+star+","+gender+","+name+","+isc1+","+isc2+","+isc3+","+isc4;
   if(fin >= 60) pass[pno++]=outstring;
   else fail[fno++]=outstring;
  }
  while ((str=bfr2.readLine())!=null) //    read a record from input file2
  {
   id=str.substring(0,8);
   gender=str.substring(8,9);
   name=str.substring(9,24);
   isc1=Integer.parseInt(str.substring(24,27));
   isc2=Integer.parseInt(str.substring(27,30));
   isc3=Integer.parseInt(str.substring(30,33));
   isc4=Integer.parseInt(str.substring(33));
   fin=finScore(isc1,isc2,isc3,isc4);
   if(gender.compareTo("M")==0) star='*';
   else star=' ';

   System.out.println(id+star+"  "+gender+" "+name+"  "+isc1+"  "+isc2+"  "+isc3+"  "+isc4+" "+fin);

   outstring=fin+","+id+star+","+gender+","+name+","+isc1+","+isc2+","+isc3+","+isc4;
   if(fin >= 60) pass[pno++]=outstring;
   else fail[fno++]=outstring;
  }
  score score1 =new score(pass, pno);
  score1.sort();
  for(int i=0;i< pno;i++){
   String[] tk=pass[i].split("[,]");
   bfw1.write(tk[1]+" "+tk[2]+" "+tk[3]+" "+tk[4]+" "+tk[5]+"  "+tk[6]+"  "+tk[0]);
   bfw1.newLine();
  }
  score score2=new score(fail, fno);
  score2.sort();
  for(int i=0;i< fno;i++){
   String[] tk=fail[i].split("[,]");
   bfw2.write(tk[1]+" "+tk[2]+" "+tk[3]+" "+tk[4]+" "+tk[5]+"  "+tk[6]+"  "+tk[0]);
   bfw2.newLine();
  }
  bfw1.flush();
  bfw2.flush();
  fr1.close();
  fw1.close();
  fr2.close();
  fw2.close();
 }
 static double finScore(int a, int b, int c, int d){
  return (int)((a*0.15+b*0.25+c*0.3+d*0.3)*100)/100.0;
 }
}


clsA

A9528003/F/Mary Chen/75/82/65/73
A9528005/M/Roney Liu/86/62/75/66
A9528006/M/CoCo Wu/43/62/45/50
A9528011/F/Jeny Kuo/95/88/93/92
A9528012/M/Johny Hu/72/66/65/73
A9528013/F/Colud Lu/53/42/35/47
A9528017/M/Beer Lee/77/66/88/54
A9528025/M/Cool Hung/43/62/45/65
A9528028/F/Fly Wang/93/82/98/85
A9528031/F/Rose Chung/82/76/67/70

clsB

A9528002MBruce Wang     075076065093
A9528008MRoney Chen     086072075057
A9528010FEdwin Liao     082086067050
A9528014FMilly Shai     095085093072
A9528018MAndy Chen      082063065073
A9528022FWoody Lu       063052035037
A9528026MBlue Cheng     071057093057
A9528030MDenny Hung     048063045045
A9528038FCandy Lin      093082088085
A9528042MAdam Wu        082088067074
A9528050FKitty Lee      042056041065

2013年5月27日 星期一

CH14 例外處理

原始檔案 加上三樣例外處理
class try0521{
        public static void main(String[] args){

 String score="75,88,62,77,69,82,79,85,93,4l,81,53,66,71";
                 String[] token=score.split("[,]");
 try{
 int num=0, sum=0;

 int[] data=new int[token.length];

 for(int i=1;i<=token.length;i++)
  data[i]=Integer.parseInt(token[i]);

 for(int dd:data) sum=sum+dd;
 System.out.println(" Average : "+sum/num);
 }catch(ArrayIndexOutOfBoundsException e){
  System.out.println(" ArrayIndexOutOfBoundsException: "+e);
 }catch(NumberFormatException  e){
  System.out.println("NumberFormatException: "+e);
 }catch(ArithmeticException e){
  System.out.println("ArithmeticException: "+e);
 } 
 

 }
}

第一點
出現以下訊息
NumberFormatException: java.lang.NumberFormatException: For input string: "4l"
String score="75,88,62,77,69,82,79,85,93,41,81,53,66,71"; 將4l改正為41之後
第二點
出現以下訊息
ArrayIndexOutOfBoundsException: java.lang.ArrayIndexOutOfBoundsException: 14
for(int i=1;i<token.length;i++)改為 i < token.length
第三點
出現以下訊息
ArithmeticException: java.lang.ArithmeticException: / by zero
加上num=token.length;

以上三點例外處理改正之後就為正常運行

2013年5月21日 星期二

物件導向期末小考5/21


class ex0423b{
        public static void main(String[] args){

 String stdRec="E9923017,Mary Wu,75,0.3,67,0.3,82,0.4";
 
                String[] token=stdRec.split("[,]");

 double fscore=0;

 int s1,s2,s3;
 double p1,p2,p3;
 s1=Integer.parseInt(token[2]);
 s2=Integer.parseInt(token[4]);
 s3=Integer.parseInt(token[6]);
 p1=Double.parseDouble(token[3]);
 p2=Double.parseDouble(token[5]);
 p3=Double.parseDouble(token[7]);
 fscore=s1*p2+s2*p2+s3*p3;

 System.out.println(" Name: "+ token[1]);
 System.out.println(" ID: "+ token[0]);
 System.out.println("     1st Score: "+ token[2]);
 System.out.println("     2nd Score: "+ token[4]);
 System.out.println("     3rd Score: "+ token[6]);
 System.out.println(" Final Score: "+ fscore); 
        }
}


class score{
 int[] sdata;
 int pvalue;

 score(int[] data){
  sdata=data;
  pvalue=60;
 }

 void setPvalue(int pp){
  this.pvalue=pp;
 }

 double getAvg(){ // Two decimal places
  int count=0,sum=0;
  for(int i:sdata) {
   sum+=i;
   count++;
  }
  return (int)((float)sum/count*100)/100.0;
 }

 int getPassNo(){
  int count=0;
  for(int i:sdata) if(i>=pvalue) count++;
  return count;
 }

}

class subScore extends score{ // inhertance super class score
// call super class constructor
 int[] sdata;
 subScore(int[] d){
  super(d);
  sdata=super.sdata;
 }
// create a method for sorting

 void sort(){
  int tmp;
  for(int i=0;i<sdata.length-1;i++){
   for(int j=i+1;j< sdata.length;j++){
    if(sdata[i] < sdata[j]){
     tmp=sdata[i];
     sdata[i]=sdata[j];
     sdata[j]=tmp;
    }
   }
  }
 }
 
 int getRank(int f){

  return sdata[f-1];
 }

 int getHigh(){

  return sdata[0];
 }
 
 int getLow(){

  return sdata[sdata.length-1];
 }
} 

class ex0430{
public static void main(String[] args) 
{
 int[] data1={75, 90, 83, 42, 66, 55, 93, 72, 88, 62, 35, 96, 81, 53, 91}; // ITMA 60
 int[] data2={78, 54, 63, 89, 79, 67, 95, 46, 93, 81, 99, 50, 70, 66, 90, 71, 88}; // ITMB 70

//
// instance an object by data1
 subScore d1 = new subScore(data1);
 d1.setPvalue(60);
 d1.sort();

// 
// instance an object by data2
 subScore d2 = new subScore(data2);
 d2.setPvalue(70);
 d2.sort();
//
 System.out.println(" Average of ITMA: "+d1.getAvg());
 System.out.println(" PassNo of ITMA: "+d1.getPassNo());
 System.out.println(" Highest score of ITMA: "+d1.getHigh());
 System.out.println(" Lowest score of ITMA: "+d1.getLow());
 System.out.println(" 3RD score of ITMA: "+d1.getRank(3));
 System.out.println(" 7th score of ITMA: "+d1.getRank(7));
 System.out.println(" ");
 System.out.println(" Average of ITMB: "+d2.getAvg());
 System.out.println(" PassNo of ITMB: "+d2.getPassNo());
 System.out.println(" Highest score of ITMB: "+d2.getHigh());
 System.out.println(" Lowest score of ITMB: "+d2.getLow());
 System.out.println(" 2nd score of ITMB: "+d2.getRank(2));
 System.out.println(" 5th score of ITMB: "+d2.getRank(5)); 
}
}

interface Ip1{
    int num=20;

    void show();
}

interface Ip2{
    int num=50;

    void show();
}

interface Ic extends Ip1, Ip2{
     void show(String ss);
}

public class ex0514 implements Ic{
      public void show(){
               show(" ");
       }
      public void show(String ss){
               System.out.println(ss+" num of Ip1 "+Ip1.num+" num of Ip2 "+Ip2.num);
       }

       public static void main(String[] argv){
 ex0514 obj=new ex0514();
 obj.show();
 obj.show(" Test ");
       }
}

abstract class Land{
        abstract double area();
 abstract double perimeter();
}

class Circle extends Land{
           double radius;

           Circle(double r){
       radius=r;
 }

 double area(){
                      return radius*radius*Math.PI;
 }

 double perimeter(){
                      return radius*2*Math.PI;
 }
}

class Square extends Land{
           double size;

           Square(double s){
       size=s;
 }

 double area(){
                      return size*size;
 }

 double perimeter(){
                      return size*4;
 }
}

class ex0514a{
 static public void main(String argv[]){
  Circle c = new Circle(5.6);    // generate a Circle object
                Square s = new Square(7.3);    // generate a Square object

                                // Output Circle's  area & perimeter (raduis is 5.6)
  System.out.println("Circle's area: "+c.area());
  System.out.println("Circle's perimeter: "+c.perimeter());
                                // Output Square's  area & perimeter (size is 7.3)
  System.out.println("Square's area: "+s.area());
  System.out.println("Square's perimeter: "+s.perimeter());
                }
}

dataB.txt

A9528003M168.5
A9528005F170.5
A9528006M185.5
A9528011M174.0
A9528012F157.0
A9528013M164.0
A9528017M177.0
A9528025F178.0
A9528028M184.0
A9528031M181.0

import java.io.*;

class ex0521a{
 public static void main(String[] args) throws IOException
 {

      FileReader fr=new FileReader("dataB.txt");     // fileA: dataB.txt
  BufferedReader bfr= new BufferedReader(fr);

  FileWriter fw = new FileWriter("reportB.txt");                   // output file: reportB.txt
  BufferedWriter bfw = new BufferedWriter(fw);

  String id,str,gen,height;
  double dheight;

  while ((str=bfr.readLine())!=null) //    read a record from fileA
  {
   id=str.substring(0,8);
   gen=str.substring(8,9);
   height=str.substring(9);
   dheight=Double.parseDouble(height);
   if(dheight >= 175.0) {
    System.out.println(id+"  "+gen+"  "+height);
    bfw.write(id+"  "+gen+"  "+height);
    bfw.newLine();
   }

  }
  bfw.flush();
  fr.close();
  fw.close();
 }
}





dataA.txt

A9528003;Mary Chen;75;82;65
A9528005;Roney Liu;86;62;75
A9528006;CoCo Wu;43;62;45
A9528011;Billy Kuo;95;88;93
A9528012;Johny Hu;72;66;65
A9528013;Chung LU;53;42;35
A9528017;Beer Lee;77;66;88
A9528025;Cool Hung;43;62;45
A9528028;Fly Wang;93;82;98
A9528031;Woody Lai;82;76;67

import java.io.*;

class score{
 double[] sc;
 score(double[] data){
  sc=data;
 }
 double getHigh(){
  double high=0;
  for(double d:sc)
   if(d>high) high=d;
  return high;
 }
 int passNo(){
  int sum=0;
  for(double d:sc)
   if(d>=60)sum++;
  return sum;
 }
}

class ex0521b{
 public static void main(String[] args) throws IOException
 {

      FileReader fr=new FileReader("dataA.txt");     // fileA: dataA.txt ==> 學生成績資料檔
  BufferedReader bfr= new BufferedReader(fr);
 
 //    將學號、成績1, 成績2, 成績3 及三科平均分數(*)、姓名
                 //     且產生平均最高分及平均及格人數寫入 fileB: report.txt  
                 // 
 //    String sc="94"
                 //     int x=Integer.parseInt(sc);      ==>    x=94;
                 //
  FileWriter fw = new FileWriter("report.txt");                   // output file: report.txt
  BufferedWriter bfw = new BufferedWriter(fw);
        //
        //    read first record 內容為學生人數 (成績筆數)
        //

  String name,id,str;
  int recno=0,isc1,isc2,isc3=0;
  double avg;
  double[] sc=new double[10];
  char star='*';

  while ((str=bfr.readLine())!=null) //    read a record from fileA
  {
   String[] token=str.split("[;]");
   id=token[0];
   name=token[1];
   isc1=Integer.parseInt(token[2]);
   isc2=Integer.parseInt(token[3]);
   isc3=Integer.parseInt(token[4]);
   avg=(int)(((double)isc1+isc2+isc3)/3.0*10)/10.0;
   if(avg<60) star='*';
   else star=' ';
   System.out.println(id+"  "+isc1+"  "+isc2+"  "+isc3+"  "+avg+"  "+name+star);
   sc[recno]=avg;
   recno++;
   bfw.write(id+"  "+isc1+"  "+isc2+"  "+isc3+"  "+avg+"   "+name+star);
   bfw.newLine();

  }
  score obj=new score(sc);
  System.out.println("最高分:"+obj.getHigh()+" 及格人數:"+ obj.passNo());
  bfw.write("最高分:"+obj.getHigh()+"及格人數:"+obj.passNo());
  bfw.newLine();
  bfw.flush();
  fr.close();
  fw.close();
 }
}



class Parent{
 int i;
 Parent(int i){
  this.i=i;
 }
 void show(){
  System.out.println(" i: "+i);
 }
}
class Child extends Parent{
 Child(){
  super(10);
 }
 Child(int i){
  super(i);
 }
}
class t0430{
 public static void main(String[] args) 
 {
  Parent obj=new Parent(99);
  obj.show();

  Child obj1=new Child(66);
  obj1.show();

  Child obj2=new Child();
  obj2.show();
 }
}


class score{
 int[] data;
 score(int[] d){    // build a constructor & set integer arrary as parameter
  data=d;
 }
 void sort(){
  int tmp;
  for(int i=0;i<data.length-1;i++){
   for(int j=i+1;j< data.length;j++){
    if(data[i] < data[j]){
     tmp=data[i];
     data[i]=data[j];
     data[j]=tmp;
    }
   }
  }
 }
}

class t0430a{
 public static void main(String[] args) 
 {
  int[] data={78, 54, 63, 89, 79, 46, 93, 81, 99, 50, 70, 66};
  for(int ss:data) System.out.print(" "+ss);
  System.out.println(" ");

  // instance an object
  // call the method of sort
  score s = new score(data);
  s.sort();

  for(int ss:data) System.out.print(" "+ss);
 }
}

assert實作

編譯為一樣javac xxxx.java 只是執行assert時須輸入 java -ea xxxx (沒加入-ea則不會有assert效果)
class assert1{
 public static void main(String[] args){
  int[] data={10,56,66,119,-5,30};
  int sum=0;
  for(int ss:data){
   assert(ss >= 100) : "data more than 100";
   assert(ss <= 0) : "data less than 0";
   sum+=ss;
  }
  System.out.println(" Sum:"+sum);
 }
}


package封裝實例

建立Circle.java和Square.java以及同目錄的Test資料夾
Circle.java
package Test;
public class Circle {
        double radius;

        public Circle(double r){
       radius=r;
 }

 public double area(){
                      return radius*radius*Math.PI;
 }

 public double perimeter(){
                      return radius*2*Math.PI;
 }
}
Square.java
package Test;
public class Square {
        double size;

        public Square(double s){
       size=s;
 }

 public double area(){
                      return size*size;
 }

 public double perimeter(){
                      return size*4;
 }
}
輸入指令 javac -d /Test Circle.java
輸入指令 javac -d /Test Square.java
將資料封裝在/Test/Test裡面並建立main.java在/Test裡(封裝資料夾外) 即可讀取
class main{
 static public void main(String argv[]){
  Test.Circle c = new Test.Circle(5.6);    // generate a Circle object
                Test.Square s = new Test.Square(7.3);    // generate a Square object

                                // Output Circle's  area & perimeter (raduis is 5.6)
  System.out.println("Circle's area: "+c.area());
  System.out.println("Circle's perimeter: "+c.perimeter());
                                // Output Square's  area & perimeter (size is 7.3)
  System.out.println("Square's area: "+s.area());
  System.out.println("Square's perimeter: "+s.perimeter());
                }
}

物件導向實例

以物件導向讀取student.class 實作test.java
class test {
 public static void main(String[] args){
  student std = new student();
  System.out.println("Name :"+std.getName());
  System.out.println("Age :"+std.getAge());
  System.out.println("Gender :"+std.getGen());

 }
}

物件導向設計原理期末考(I)


1. 將兩班成績分數透過切割函數,切割成小字串,整數字串轉成整數且存於整數陣列,
(a) 將整數陣列當作score建構方法參數,且產生一score物件。
(b) 再透過score物的成員方法完成題目的要求。
   class score包括:
一個資料成員:
int[] data;
  一個建構方法:
score(int[] dd)    // 設定int[] data初始值
兩個成員方法:
getLevelNum( base)     // 傳回整數 base (含)分數以上人數
getPassAvg() // 傳回及格成績的平均分數(小數後兩位)



class score{
 int[] data;

 score(int[] dd){
  data=dd;
 }
 int getLevelNum(int base){
  int num=0;

  for(int kk:data) 
   if(kk >= base) num++;
  return num;
 }

 double getPassAvg(){
  int sum=0, num=0;
  
  num=getLevelNum(60);
  for(int i:data) {
   if(i>=60) sum+=i; 
  }
  return (int)((double)sum/num*100)/100.0;
 }
}

class prob10507{
        public static void main(String[] args){

 String IMDA="IMDA,75,88,62,77,69,82,79,85,93,44,81,53,66,71";
 String IMDB="IMDB/55/68/72/57/83/77/93/75/66/85/83/47/52/87/96/53/62/89/76/51";
 int gradeA, gradeB, gradeC, gradeD,gradeF; 

        String[] token=IMDA.split("[,]");
 int[] data=new int[token.length-1];

 for(int i=1;i<token.length;i++)
  data[i-1]=Integer.parseInt(token[i]);

 score cls1=new score(data);
                gradeA=cls1.getLevelNum(90);
                gradeB=cls1.getLevelNum(80)-cls1.getLevelNum(90);
                gradeC=cls1.getLevelNum(70)-cls1.getLevelNum(80);
                gradeD=cls1.getLevelNum(60)-cls1.getLevelNum(70);
                gradeF=cls1.getLevelNum(0)-cls1.getLevelNum(60);
 System.out.println(" CLS Name: "+ token[0]);
 System.out.println("     Numbers of students: "+ (token.length-1));
 System.out.println("     Pass Average Number: "+cls1.getPassAvg());
 System.out.println("     grade A Number: "+gradeA);    // score >= 90
 System.out.println("     grade B Number: "+gradeB);    // score >= 80 and score < 90
 System.out.println("     grade C Number: "+gradeC);    // score >= 70 and score < 80
 System.out.println("     grade D Number: "+gradeD);   // score >= 60 and score < 70
 System.out.println("     grade F Number: "+gradeF);    // score < 60

        String[] token2=IMDB.split("[/]");
 int[] data2=new int[token2.length-1];

 for(int i=1;i<token2.length;i++)
  data2[i-1]=Integer.parseInt(token2[i]);

 score cls2=new score(data2);
                gradeA=cls2.getLevelNum(90);
                gradeB=cls2.getLevelNum(80)-cls2.getLevelNum(90);
                gradeC=cls2.getLevelNum(70)-cls2.getLevelNum(80);
                gradeD=cls2.getLevelNum(60)-cls2.getLevelNum(70);
                gradeF=cls2.getLevelNum(0)-cls2.getLevelNum(60);
 System.out.println(" CLS Name: "+ token2[0]);
 System.out.println("     Numbers of students: "+ (token2.length-1));
 System.out.println("     Pass Average Number: "+cls2.getPassAvg());
 System.out.println("     grade A Number: "+gradeA);
 System.out.println("     grade B Number: "+gradeB);
 System.out.println("     grade C Number: "+gradeC);
 System.out.println("     grade D Number: "+gradeD);
 System.out.println("     grade F Number: "+gradeF);
        }
}



2. (a) class degree 包括:
  一個建構方法:
degree( char, double)    // 設定degreeC, degreeF 初始值
兩個資料成員:
private: double degreeC, degreeF;
  四個成員方法:
private:  CtoF()    // degreeC  degreeF
private:  FtoC()    // degreeF  degreeC
public: getDegC()    // 傳回degreeC
public: getDegF()    // 傳回degreeF
(b) class check 繼承degree
  一個建構方法:
check(char, double)  //呼叫父類別之建構方法,設定degreeC, degreeF 初始值
有兩個成員方法:
public:  degChk()          // 傳回體溫狀態代碼(整數)
public:  toStatus(byte)    // 傳回體溫狀態(字串)
(c) 透過相關的成員方法完成題目要求(產業輸出內容)。

體溫、代碼與狀態對照表
~ 36.4c (97.5f)     -1 (Hypothermia) (體溫過低)
36.4c (97.5f) ~ 37.8c (100f)   0 (Normal) (正常)
37.8c (100.f) ~ 39.4c (103.0f)   1 (Fever) (發燒)
39.4c (103.0f) ~ 40.3c (104.5f)   2 (High Fever) (高燒)
40.3c (104.5f) ~               3 (Serious) (嚴重)



class degree{
 private double degC=0, degF=32;

 degree(char CF, double dd){
  if(CF=='C'){
   degC=dd;
   CtoF();
  }else if(CF=='F'){
   degF=dd;
   FtoC();
  }
 }
 private void CtoF(){
  degF=degC*5.0/9.0+32;
 }
 private void FtoC(){
  degC=(degF-32)/9.0*5.0;
 }
 double getDegC(){
  return degC;
 }
 double getDegF(){
  return degF;
 }
}

class check extends degree{
 check(char cc, double dd){
  super(cc,dd);
 }
  
 byte degChk(){               // if-else statement 
                double degC=getDegC();            // call getDegC to get degC
  if(degC < 36.4) return -1;
                else if(degC < 37.8) return 0;
                else if(degC < 39.4) return 1;
                else if(degC < 40.3) return 2;
                else return 3;

 }
 String toStatus(byte n){     // switch case statement
  switch(n){
  case -1:
   return "Hypothermia";
  case 0:
   return "Normal";
  case 1:
   return "Fever";
  case 2:
   return "High Fever";
  default:
   return "Serious";
  }
 } 
}
 
class prob20507{
        public static void main(String[] args){

  check c1 =new check('C',38.3);

 System.out.println(" degree C "+c1.getDegF());
 System.out.println(" degree F "+c1.getDegC());
 System.out.println("   Status code: "+ c1.degChk());
 System.out.println("   Degree Status: "+c1.toStatus(c1.degChk()));

 check c2 = new check('F',103.5);
 System.out.println(" degree C "+c2.getDegF());
 System.out.println(" degree F "+c2.getDegC());
 System.out.println("   Status code: "+ c2.degChk());
 System.out.println("   Degree Status: "+c2.toStatus(c2.degChk())); 
        }
}