Re: [問題]關於多形和超載 程式碼問題

看板java作者時間19年前 (2006/05/23 04:32), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
※ 引述《cscfish (雙棲動物)》之銘言: > ※ 引述《cscfish (雙棲動物)》之銘言: > > 就是為啥我計算出的數字都會是0 是哪要改嗎 > > 還有說要用多形和超載 那應該超載已經合多型條件了吧 > > 如果不合條件 那要怎麼改才可以呢 > > 因為getarea() 同時有計triangle circle rectangle的不同功能(多形) > > class shape { > > private double area,circum; > > shape(double a,double b) > > { > > this.area=a; > > this.circum=b; > > } > > public double getarea(){return area;} > > double getcircum(){return circum;} > > } > > ===================================================== > > class circle extends shape { > > private double r; > > circle(double r) > > {super(r,r);} > > public double getarea(){return 3.14*r*r;} > > public double getcircum(){return 6.28*r;}; > > } > > ===================================================== > > class rectangle extends shape{ > > private double x,y; > > rectangle(double x,double y) > > {super(x,y);} > > public double getarea(){return x*y;} > > public double getcircum(){return 2*x+2*y;}; > > } > > ===================================================== > > class triangle extends shape { > > double s,t; > > triangle(double s,double t) > > { super(s,t);} > > public double getarea(){return 0.5*s*t;} > > public double getcircum(){return 3*s;}; > > } > > ===================================================== > > public class calculate { > > public static void main(String args[]){ > > circle cir=new circle(3); > > triangle tri=new triangle(3,3); > > rectangle rec=new rectangle(3,3); > > System.out.print("\n" +cir.getarea()); > > System.out.print("\n" +cir.getcircum()); > > System.out.print("\n" +tri.getarea()); > > System.out.print("\n" +tri.getcircum()); > > System.out.print("\n" +rec.getarea()); > > System.out.print("\n" +rec.getcircum()); > > } > > } 接著我要加一功能就是隨便選一個圖形 在計算其面積 我改這樣不行 不知哪位大大可以在幫指點一下 class calculate { public static void main(String args[]){ System.out.print("input integer of n"); int n=Integer.parseInt(keyin.readLine());//讀取輸入並存取n變數 //int circle=1,rectangle=2,triangle=3; int create(n) { switch(n) { case 1: System.out.print("\n" +cir.getarea(3)); System.out.print("\n" +cir.getcircum(3)); case 2: System.out.print("\n" +tri.getarea(3,3)); System.out.print("\n" +tri.getcircum(3,3)); case 3: System.out.print("\n" +rec.getarea(3,3)); System.out.print("\n" +rec.getcircum(3,3)); } } } } -- 夫兵者不祥之器物或惡之故有道者不處君子居則貴左用兵則貴右兵者不祥之器非君子 之器不得已而用之恬淡為上勝而不美而美之者是樂殺人夫樂殺人者則不可得志於天下 矣吉事尚左凶事尚右偏將軍居左上將軍居右言以喪禮處之殺人之眾以哀悲泣之戰勝以 喪禮處之道常無名樸雖小天下莫能臣侯王若能守之萬物將自賓天地相合以降甘露民莫 之令而自均始制有名名亦既有夫亦將知止知止可以不殆 173-208.dorm.ncu.edu.tw
文章代碼(AID): #14SX_300 (java)
文章代碼(AID): #14SX_300 (java)