Java语言程序设计 辛运帏 饶一梅 第八章新
- 格式:ppt
- 大小:6.52 MB
- 文档页数:72
第二章习题2.2import java.util.*;classMyDate{privat e int year;privat e int month;privat e int day;public MyDate(int y,int m,int d){//构造函数,构造方法year=y;month=m;day=d;}//end public MyDate(int y,int m,int d)public i nt getY ea r(){//返回年return year;}//end getY ea r()public i nt getMon th(){//返回月return month;}//end getMon th()public i nt getDay(){//返回日return day;}//end getDay()}//end classMyDateclassEmploy ee{privat e String name;privat e double salary;privat e MyDate hi reDa y;public Employ ee(String n,double s,MyDate d){name=n;salary=s;hireDa y=d;}//end public Employ ee(String n,double s,MyDate d)public void print(){System.out.printl n("名字:"+name+"\n工资:"+salary+"\n雇佣年份:"+hireYear()+"\n");}//end print()public void raiseS alary(double byPercent){salary*=1+byPerc ent/100;}//endpublic i nt hireYe ar(){return hireDa y.getY ea r();}}//end classEmploy eepublic classMyTest Class {public static void main(String[] args) {Employee[]staff=new Employ ee[3];staff[0]=new Employ ee("HarryH acker",35000,new MyDate(1989,10,1));staff[1]=new Employ ee("Carl Carcke r",75000,new MyDate(1987,12,15));staff[2]=new Employ ee("Tony Tester",38000,new MyDate(1990,3,12));int intege rV alu e;System.out.printl n("The inform ation of employ ee are:");for(intege rV alu e=0;intege rV alu e<=2;intege rV alu e++){staff[i ntege rV alu e].raiseS alary(5);}//end for()for(intege rV alu e=0;intege rV alu e<=2;intege rV alu e++){staff[i ntege rV alu e].print();}//end for()}//end main()}//end classMyTestClass//习题2.4import java.util.*;public classDataTy pe {public static void main(String[] args) {boolea n flag;char yesCha r;byte finByte;int intV al ue;long longValue;short shortV alue;float fl oatV alue;double double V alue;flag=true;yesCha r='y';finByt e=30;intV al ue=-7000;longVal ue=200l;shortV alue=20000;floatV alue=9.997E-5f;double V alue=floatV alue*floatV alue;System.out.printl n("the values are:");System.out.printl n("布尔类型变量fl ag="+flag);System.out.printl n("字符型变量y e sCha r="+yesCha r);System.out.printl n("字节型变量fi nByt e="+finByt e);System.out.printl n("整型变量in tV alu e="+intV al ue);System.out.printl n("长整型变量l ongVal ue="+longVal ue);System.out.printl n("短整型变量s hortV alue="+shortV alue);System.out.printl n("浮点型变量fl oatV alue="+floatV alue);System.out.printl n("双精度浮点型变量dou bleVal ue="+doubleV alue); }//end main()}//习题2.9import java.util.*;classPubTest1{privat e int ivar1;privat e float fvar1,fvar2;public PubTest1(){fvar2=0.0f;}public float sum_f_I(){fvar2=fvar1+i var1;return fvar2;}public void print(){System.out.printl n("fvar2="+fvar2);}public void setIva r1(int ivalue){ivar1=i value;}public void setFva r1(floati value){fvar1=i value;}}public classPubMai nTest {public static void main(String[] args) {PubTest1 pubt1=new PubTest1();pubt1.setIva r1(10);pubt1.setFva r1(100.02f);pubt1.sum_f_I();pubt1.print();}}//习题2.10import java.util.*;classDate {privat e int year;privat e int month;privat e int day;public Date(int day, int month, int year) { //构造函数,构造方法this.year = year;this.month= month;this.day = day;} //end public MyDate(int y,int m,int d)public i nt getY ea r() { //返回年return year;} //end getY ea r()public i nt getMon th() { //返回月return month;} //end getMon th()public i nt getDay() { //返回日return day;} //end getDay()} //end classDatepublic class Teache r {String name;//教师名字boolea n sex;//性别,true表示男性Date birth;//出生日期String salary ID;//工资号String depart;//教师所在系所String posit;//教师职称String getNam e() {return name;}void setNam e(String name) { = name;}boolea n getSex() {return sex;}void setSex(boolea n sex) {this.sex = sex;}Date getBirth() {return birth;}void setBirth(Date birth) {this.birth= birth;}String getSal aryID() {return salary ID;}void setSal aryID(String salary ID) {this.salary ID = salary ID;}String getDep art() {return depart;}void setDep art(String depart) {this.depart = depart;}String getPosi t() {return posit;}void setPosi t(String posit) {this.posit = posit;}public Teache r(){System.out.printl n("父类无参数的构造方法!!!!!!!"); }//如果这里不加上这个无参数的构造方法将会出错!!!!public Teache r(String name,boolea n sex,Date birth,String salary i d,String depart,String posit){ =name;this.sex=sex;this.birth=birth;this.salary ID=salary i d;this.depart=depart;this.posit=posit;}//end Teache r()public void print(){System.out.print("the teache r'name:");System.out.printl n(this.getNam e());System.out.print("the teache r'sex:");if(this.getSex()==false){System.out.printl n("女");}else{System.out.printl n("男");}System.out.print("the teache r'birth:");System.out.printl n(this.getBirth().getY ea r()+"-"+this.getBirth().getMon th()+"-"+this.getBirth().getDay());System.out.print("the teache r'salary i d:");System.out.printl n(this.getSal aryID());System.out.print("the teache r'posit:");System.out.printl n(this.getPosi t());System.out.print("the teache r'depart:");System.out.printl n(this.getDep art());}//end print()public static void main(String[] args) {Date dt1=new Date(11,23,1989);Date dt2=new Date(2,6,1975);Date dt3=new Date(11,8,1964);Date dt4=new Date(10,4,1975);Date dt5=new Date(8,9,1969);//创建各系教师实例,用来测试Teache r t1=new Teache r("王莹",false,dt1,"123","经济学","prefessor");Resear chTea cher rt=new Resear chTea cher("杨zi青",true,dt2,"421","软件工程","associ ate prefessor","softwa re");LabTea cherl at=new LabTea cher("王夏瑾",false,dt3,"163","外语","pinstru cor","speech lab");LibTea cherl i t=new LibTea cher("马二孩",true,dt4,"521","大学物理","prefessor","physic alLib");AdminT eache r at=new AdminT eache r("王xi",false,dt5,"663","环境","prefessor","dean");/////////分别调用各自的输出方法,输出相应信息////////////////////////////System.out.printl n("-------------------------------");t1.print();//普通教师信息System.out.printl n("-------------------------------");rt.print();//研究系列教师信息System.out.printl n("-------------------------------");lat.print();//普通教师信息System.out.printl n("-------------------------------");lit.print();//实验系列教师信息System.out.printl n("-------------------------------");at.print();//行政系列教师信息System.out.printl n("-------------------------------");}//end main()}//end public classTeache rclassResearchTea cher extend s Teache r{privat e String resFie l d;public Resear chTea cher(String name, boolea n sex, Date birth, String salary i d,String depart, String posit, String resFie l d) { = name;this.sex = sex;this.birth= birth;this.salary ID = salary i d;this.posit = posit;this.resFie l d = resFie l d;} //end public ResearchTea cher(){}String getResField(){return resFie l d;}void setResField(String resFie l d){this.resFie l d=resFie l d;}public void print() {System.out.print("research teache r info is:");System.out.print("the teache r'name:");System.out.printl n(this.getNam e());System.out.print("the teache r'sex:");if (this.getSex() == false) {System.out.printl n("女");}else {System.out.printl n("男");}System.out.print("the teache r'birth:");System.out.printl n(this.getBirth().getY ea r() + "-" +this.getBirth().getMon th() + "-" +this.getBirth().getDay());System.out.print("the teache r'salary i d:");System.out.printl n(this.getSal aryID());System.out.print("the teache r'posit:");System.out.printl n(this.getPosi t());System.out.print("the teache r'depart:");System.out.printl n(this.getDep art());System.out.print("the teache r'resFie l d:");System.out.printl n(this.getResField());} //end print()}//end classResear chTea cherclassLabTea cherextend s Teache r{privat e String labNam e;public LabTea cher(String name, boolea n sex, Date birth,String salary i d, String depart,String posit, String labNam e) { = name;this.sex = sex;this.birth= birth;this.salary ID = salary i d;this.posit = posit;bNam e = labNam e;} //end public ResearchTea cher(){}String getLab Name(){return labNam e;}void setLab Name(S tring labNam e){bNam e=labNam e;}public void print() {System.out.print("lab teache r info is:");System.out.print("the teache r'name:");System.out.printl n(this.getNam e());System.out.print("the teache r'sex:");if (this.getSex() == false) {System.out.printl n("女");}else {System.out.printl n("男");}System.out.print("the teache r'birth:");System.out.printl n(this.getBirth().getY ea r() + "-" +this.getBirth().getMon th() + "-" +this.getBirth().getDay());System.out.print("the teache r'salary i d:");System.out.printl n(this.getSal aryID());System.out.print("the teache r'posit:");System.out.printl n(this.getPosi t());System.out.print("the teache r'depart:");System.out.printl n(this.getDep art());System.out.print("the teache r'labNam e:");System.out.printl n(bName);} //end print()}//end classLabTea cherclassLibTea cher extend s Teache r{privat e String libNam e;public LibTea cher(String name,boolea n sex,Date birth,String salary i d,String depart,String posit,String libNam e){ = name;this.sex = sex;this.birth= birth;this.salary ID = salary i d;this.posit = posit;this.libNam e=libNam e;}//end public Resear chTea cher(){}String getLib Name(){return libNam e;}void setLib Name(String libNam e){this.libNam e=libNam e;}public void print() {System.out.print("lib teache r info is:");System.out.print("the teache r'name:");System.out.printl n(this.getNam e());System.out.print("the teache r'sex:");if (this.getSex() == false) {System.out.printl n("女");}else {System.out.printl n("男");}System.out.print("the teache r'birth:");System.out.printl n(this.getBirth().getY ea r() + "-" +this.getBirth().getMon th() + "-" +this.getBirth().getDay());System.out.print("the teache r'salary i d:");System.out.printl n(this.getSal aryID());System.out.print("the teache r'posit:");System.out.printl n(this.getPosi t());System.out.print("the teache r'depart:");System.out.printl n(this.getDep art());System.out.print("the teache r'libNam e:");System.out.printl n(this.libNam e);} //end print()}//end classLibTea cherclassA dminT eache r extend s Teache r{privat e String manage Pos;public AdminTeache r(String name,boolea n sex,Date birth,String salary i d,String depart,String posit,String manage Pos){ = name;this.sex = sex;this.birth= birth;this.salary ID = salary i d;this.depart = depart;this.posit = posit;this.manage Pos=manage Pos;}//end public Resear chTea cher(){}String getMan agePo s(){return manage Pos;}void setMan agePo s(String manage Pos){this.manage Pos=manage Pos;}public void print() {System.out.print("admint eache r info is:");System.out.print("the teache r'name:");System.out.printl n(this.getNam e());System.out.print("the teache r'sex:");if (this.getSex() == false) {System.out.printl n("女");}else {System.out.printl n("男");}System.out.print("the teache r'birth:");System.out.printl n(this.getBirth().getY ea r() + "-" +this.getBirth().getMon th() + "-" +this.getBirth().getDay());System.out.print("the teache r'salary i d:");System.out.printl n(this.getSal aryID());System.out.print("the teache r'posit:");System.out.printl n(this.getPosi t());System.out.print("the teache r'depart:");System.out.printl n(this.getDep art());System.out.print("the teache r'manage Pos:");System.out.printl n(this.manage Pos);} //end print()}//end classA dminT eache r习题2.11public classCourse {privat e String course ID;privat e String course Name;privat e String course Type;privat e int classH our;privat e float credit;public Course(String course ID, String course Name, String course Type, int classH our, float credit) {this.course ID=course ID;this.course Name=course Name;this.course Type=course Type;this.classH our=classH our;this.credit=credit;}//end public Course(){}String getID() {return course ID;}void setID(String id) {this.course ID = id;}String getNam e() {return course Name;}void setNam e(String name) {this.course Name= name;}String getType() {return course Type;}void setTyp e(String type) {this.course Type= type;}int getCla ssHou r() {return classH our;}void setCla ssHou r(int hour) {this.classH our = hour;}float getCre dit() {return classH our;}void setCre dit(float credit) {this.credit= credit;}public void print(){System.out.printl n("the basici nfo of this course as followed:"); System.out.printl n("course ID="+this.getID());System.out.printl n("course Name="+this.getNam e());System.out.printl n("course Type="+this.getType());System.out.printl n("classH our="+this.getCla ssHou r());System.out.printl n("credit="+this.getCre di t());}public static void main(String[] args) {Course cs=new Course("d12","java程序设计(第二版)","cs",64,3.0f);System.out.printl n("----------------------------------");cs.print();System.out.printl n("修改课程学分为4.0f");cs.setCre dit(4);cs.print();}}//习题2.12public classMyGrap hi c {String lineCol or;String fillCol or;MyGrap hic(String l c,String fc){this.lineCol or=lc;this.fillCol or=fc;}void print(){System.out.printl n("line colori s "+this.lineCol or+"\t fill colori s "+this.fillCol or);}public static void main(String[] args) {float rd=(float)4.5;MyCircl e mc=new MyCircl e(rd,"black","white");MyRect angle mr=new MyRect angle(4,6,"red","blue");System.out.printl n("Circle info ");mc.print();System.out.printl n("circum feren ce is " + mc.calCir cum());System.out.printl n("square i s " + mc.calSquare());System.out.printl n("rectan gle info: ");mr.print();System.out.printl n("circum feren ce is " + mr.calCir cum());System.out.printl n("square i s " + mr.calSqu are());}//end main(){}}//end public classMyGrap hicclassMyRectangle extend s MyGrap hi c{float rLong;float rWidth;MyRect angle (float rl,float rw,String l c,String fc){super(l c,fc);this.rLong=rl;this.rWidth=rw;}//end MyRectangle (){}float calCir cum(){return ((float)((this.rLong+this.rWidth)*2));}float calSqu are(){return ((float)(this.rLong*this.rWidth));}}//end classMyRect angleclassMyCircl e extend s MyGrap hi c{float radius;MyCircl e (float rd,String l c,String fc){super(l c,fc);this.radius=rd;}//end MyRectangle (){}float calCir cum(){return (float)((this.radius*3.12*2));}float calSqu are(){return ((float)(this.radius*this.radius*3.14));}}//end classMyCircl e//习题2.13public classV ehicl e {String brand;String color;int price;int number;public V ehicl e(String b, String c) {this.brand= b;this.color = c;}public V ehicl e(String b, String c, int p, int n) {this(b, c);this.price= p;this.number = n;}void print() {System.out.printl n("\n-------------------------");System.out.printl n("the vehicl e info as followed :");System.out.printl n("brand=" + this.brand+ "\t");System.out.printl n("color=" + this.color+ "\t");System.out.printl n("price=" + this.price+ "\t");System.out.printl n("number=" + this.number + "\t"); } //end void print()public static void main(String[] args) {V ehicl e c1=new V ehicl e("vehicl e1","white");V ehicl e c2=new V ehicl e("vehicl e2","white",300,1);Car cr=new Car("car1","red",300,4,400);Trucktk2=new Truck("truck1","black",300,400);c1.print();c2.print();cr.print();tk2.print();} //end main()} //end public classV ehicl eclassCar extend s V ehicl e{int speed;Car(String b, String c, int p, int n,int s){super(b,c,p,n);this.speed=s;}void print(){super.print();System.out.print("speed="+this.speed);}}//end classCarclass Truckextend s V ehicl e{int speed;int weight;Truck(String b, String c, int s,int w){super(b,c);this.speed=s;this.weight=w;}void print(){super.print();System.out.print("speed="+this.speed);System.out.print("weight="+this.weight);}}//end class Truck第三章习题3.3public class Test {public static void main(String[] args) {int b1=1;int b2=1;System.out.printl n("b1=" + b1);System.out.printl n("b2=" + b2);b1<<=31;b2<<=31;System.out.printl n("b1=" + b1);System.out.printl n("b2=" + b2);b1 >>= 31;System.out.printl n("b1=" + b1);b1 >>= 1;System.out.printl n("b1=" + b1);b2 >>>= 31;System.out.printl n("b2=" + b2);b2 >>>= 1;System.out.printl n("b2=" + b2);}}//习题3.4public classFactori al {privat e int result,initVal;public static int Factori al(int n){if(n==0){return 1;}return n*Factori al(n-1);}public void print(){System.out.printl n(initVal+"!="+result); }public void setIni tV al(i nt n){initVal=n;}public static void main(String[] args) {Factori al ff=new Factori al();for(int i=0;i<=4;i++){ff.setIni tV al(2*(i+1));ff.result=Factorial(ff.initVal);ff.print();}//end for()}//end main()}//end public classFactori alpublic classFactori al2{privat e int result,initVal;public void print(){System.out.printl n(initVal+"!="+result); }public void setIni tV al(i nt n){initVal=n;}public static void main(String[] args) { Factori al2ff=new Factorial2();for(int i=0;i<=4;i++){ff.setIni tV al(2*(i+1));ff.result=1;for(int j=2;j<=ff.initVal;j++){ff.result*=j;}ff.print();}//end for()}//end main()}//习题3.5public classMathRa ndomT est {public static void main(String[] args) {int count=0,MAXof100,MINof100;int num,i;MAXof100=(int)(100*Math.random());MINof100=(int)(100*Math.random());System.out.print(MAXof100+" ");System.out.print(MINof100+" ");if(MAXof100>50)count++;if(MINof100>50)count++;if( MAXof100<MINof100){num=MINof100;MINof100=MAXof100;MAXof100=num;}//end if()for(i=0;i<98;i++){num=(int)(100*Math.random());System.out.print(num+((i+2)%10==9?"\n":" "));if(num>MAXof100){MAXof100=num;}else if(num<MINof100){MINof100=num;}if(num>50){count++;}}//end for()System.out.printl n("the max of 100 random intege rs i s "+MAXof100);System.out.printl n("the min of 100 random intege rs is "+MINof100);System.out.printl n("the number of random more than50 is "+count); }//end main()}//end public classMathRa ndomT est//习题3.7public classP rintA st {public void printA star() {System.out.print("*");}public void printS pace() {System.out.print(" ");}public static void main(String[] args) {PrintA st pa = new PrintA st();int initNu m = 13;for (int i = 1; i <= initNu m / 2 + 1; i++) {for (int n = 1; n <= i; n++) {pa.printS pace();pa.printS pace();}for (int m = 1; m <= initNu m - 2 * i + 2; m++) {pa.printS pace();pa.printA star();}System.out.printl n();} //end forif (initNu m % 2 == 0) {for (int i = 1; i <= initNu m / 2; i++) {pa.printS pace();pa.printS pace();}pa.printS pace();pa.printA star();pa.printS pace();pa.printA star();System.out.printl n();}for (int i = initNu m / 2 + 2; i <= initNu m; i++) {for (int n = 1; n <= initNu m - i + 1; n++) {pa.printS pace();pa.printS pace();}for (int m = 1; m <= 2 * i - initNu m; m++) {pa.printS pace();pa.printA star();}System.out.printl n();} //end forSystem.out.printl n();} //end main()} //end public class PrintA st//习题3.8public classP rintT riag{public void printA star() {System.out.print("*");}public static void main(String[] args) {int initLi ne = 10;int initNu m = 10;PrintT riagpt = new PrintT riag();for (int i = 0; i < initLi ne; i++) {for (int j = 0; j < initNu m - i; j++) {pt.printA star();}System.out.printl n();}}//end main()}//end public classPrintT riag习题3.9import java.util.*;public classMultip l eTab l e {public void printF ormul a(int i,int j,int res){System.out.print(i+"*"+j+"="+res+" "); }public static void main(String[] args) {Multip l eTab l e mt=new Multip leTab le();int initNu m=9;int res=0;for(int i=1;i<=initNu m;i++){for(int j=1;j<=i;j++){res=i*j;mt.printF o rmul a(i,j,res);}System.out.printl n();}//end for}//end main()}//end public classMultip l eTab l e习题3,10import java.io.*;public classH uiWen {boolea n isHuiW en(char str[], int n) {int net = 0;int i, j;for (i = 0, j = n - 1; i < n / 2; i++, j--) {if (str[i] == str[j]) {net++;} //end if} //end forif (net == (int) (n / 2)) {return true;} //end ifelse {return false;}} //end boolea n isHuiW en(char str[], int n) public static void main(String[] args) {HuiWen hw1 = new HuiWen();String pm = "";try {InputS tream Reade r reader = new InputS tream Reade r(System.in);BufferedRea der input = new BufferedRea der(reader);System.out.print("give your test string:\n");pm = input.readLi ne();System.out.printl n(pm);} //end trycatch (IOExce ption e) {System.out.print(e);} //end catchboolea n bw = hw1.isHuiW en(pm.toCharA rray(), pm.length());if (bw == true) {System.out.printl n("是回文");}else {System.out.printl n("不是回文");}} //end main()} //end public classH uiWenimport java.io.*;public classH uiWen2 {String reverse(String w1){String w2;char[]str1=w1.toCharA rray();int len=w1.length();char[]str2=new char[len];for(int i=0;i<len;i++){str2[i]=str1[len-1-i];}w2=new String(str2);return w2;}public static void main(String[] args) {HuiWen2 hw1 = new HuiWen2();String pm = "";try {InputS tream Reade r reader = new InputS tream Reade r(System.in);BufferedRea der input = new BufferedRea der(reader);System.out.print("give your test string:\n");pm = input.readLi ne();} //end trycatch (IOExce ption e) {System.out.print(e);} //end catchString w2=hw1.reverse(pm);if(pareTo(pm)==0){System.out.printl n("是回文");}else {System.out.printl n("不是回文");}}}//习题3.11import java.io.*;public classP rimeN umber {privat e int pm;public void setPm(i nt pm){this.pm=pm;}public boolea n isPrim e(){boolea n bl=true;int i=2;for(i=2;i<=Math.sqrt(pm);){if(pm%i==0){bl=false;break;}else{i++;}}//end forreturn bl;}//end public boolea n isPrim e()public static void main(String[] args) {PrimeN umber prim=new PrimeN umber();int testNu m=0;try{InputS tream Reade r reader = new InputS tream Reade r(System.in);BufferedRea der input = new BufferedRea der(reader);System.out.print("give your test number:\n");testNu m=Intege r.parseInt(input.readLi ne());}//end trycatch(IOExce ption e){System.out.printl n(e);}//end catchprim.setPm(testNu m);。
Java语言程序设计(郑莉)第八章课后习题答案1.进程和线程有何区别,Java是如何实现多线程的。
答:区别:一个程序至少有一个进程,一个进程至少有一个线程;线程的划分尺度小于进程;进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。
Java程序一般是继承Thread类或者实现Runnable接口,从而实现多线程。
2.简述线程的生命周期,重点注意线程阻塞的几种情况,以及如何重回就绪状态。
答:线程的声明周期:新建-就绪-(阻塞)-运行--死亡线程阻塞的情况:休眠、进入对象wait池等待、进入对象lock池等待;休眠时间到回到就绪状态;在wait池中获得notify()进入lock池,然后获得锁棋标进入就绪状态。
3.随便选择两个城市作为预选旅游目标。
实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。
分别用Runnable接口和Thread类实现。
(注:两个类,相同一个测试类)//Runnable接口实现的线程runable类publicclarunnableimplementRunnable{privateStringcity;publicr unnable(){}publicrunnable(Stringcity){thi.city=city;}publicvoidrun(){for(inti=0;i<10;i++){Sytem.out.println(city);try{//休眠1000毫秒。
Thread.leep(1000);}catch(InterruptedE某ceptione){e.printStackTrace();}}}}//Thread类实现的线程thread类publicclarunnablee某tendThread{privateStringcity;publicrunnable(){}publicrunnable(Stringcity){thi.city=city;}publicvoidrun(){for(inti=0;i<10;i++){Sytem.out.println(city);try{//休眠1000毫秒。
Java程序设计实用教程(第4版)习题解答与实验指导叶核亚编著2013年11月目录“Java程序设计”课程教学要求 (1)第1章 Java概述 (3)第2章 Java语言基础 (5)第3章类的封装、继承和多态 (23)第4章接口、内部类和 Java API基础 (40)第5章异常处理 (45)第6章图形用户界面 (47)第7章多线程 (52)第8章输入/输出流和文件操作 (54)“Java程序设计”课程教学要求1. 课程性质、目的和任务程序设计是高等学校计算机学科及电子信息学科各专业本科的核心专业基础课程,是培养学生软件设计能力的重要课程。
在计算机学科的本科教学中,起着非常重要的作用。
“Java程序设计”是计算机科学与技术专业本科的专业基础限选课,开设本课程的目的是:进行程序设计和面向对象方法的基础训练;使用Java编程技术,设计解决操作系统、网络通信、数据库等多种实际问题的应用程序。
本课程通过全面、系统地介绍Java语言的基础知识、运行机制、多种编程方法和技术,使学生理解和掌握面向对象的程序设计方法,理解和掌握网络程序的特点和设计方法,建立起牢固扎实的理论基础,培养综合应用程序的设计能力。
本课程的先修课程包括:C/C++程序设计I、C/C++程序设计II、数据结构、操作系统、计算机网络、数据库原理等。
2. 教学基本要求本课程的基本要求如下。
①了解Java语言特点,理解Java Application应用程序的运行原理和方法。
掌握在JDK环境中编译和运行程序的操作,熟悉在MyEclipse集成开发环境中,编辑、编译、运行和调试程序的操作。
②掌握Java语言中语句、数组、引用类型等基本语法成分的使用方法,通过类、接口、内嵌类型、包、异常处理等机制表达和实现面向对象程序设计思想。
③掌握Java的多种实用技术,包括图形用户界面、多线程、文件操作和流、使用URL 和Socket进行网络通信等。
④熟悉Java JDBC数据库应用的设计方法。
以下是《Java程序设计》(第二版)的全部课后答案,不包括简答题,概念题,只是程序设计题目。
//习题2.2import java.util.*;class MyDate{private int year;private int month;private int day;public MyDate(int y,int m,int d){//构造函数,构造方法year=y;month=m;day=d;}//end public MyDate(int y,int m,int d)public int getYear(){//返回年return year;}//end getYear()public int getMonth(){//返回月return month;}//end getMonth()public int getDay(){//返回日return day;}//end getDay()}//end class MyDateclass Employee{private String name;private double salary;private MyDate hireDay;public Employee(String n,double s,MyDate d){name=n;salary=s;hireDay=d;}//end public Employee(String n,double s,MyDate d)public void print(){System.out.println("名字:"+name+"\n工资:"+salary+"\n雇佣年份:"+hireYear()+"\n");}//end print()public void raiseSalary(double byPercent){salary*=1+byPercent/100;}//endpublic int hireYear(){return hireDay.getYear();}}//end class Employeepublic class MyTestClass {public static void main(String[] args) {Employee[]staff=new Employee[3];staff[0]=new Employee("Harry Hacker",35000,new MyDate(1989,10,1));staff[1]=new Employee("Carl Carcker",75000,new MyDate(1987,12,15));staff[2]=new Employee("Tony Tester",38000,new MyDate(1990,3,12));int integerValue;System.out.println("The information of employee are:");for(integerValue=0;integerValue<=2;integerValue++){staff[integerValue].raiseSalary(5);}//end for()for(integerValue=0;integerValue<=2;integerValue++){staff[integerValue].print();}//end for()}//end main()}//end class MyTestClass//习题2.4import java.util.*;public class DataType {public static void main(String[] args) {boolean flag;char yesChar;byte finByte;int intValue;long longValue;short shortValue;float floatValue;double doubleValue;flag=true;yesChar='y';finByte=30;intValue=-7000;longValue=200l;shortValue=20000;floatValue=9.997E-5f;doubleValue=floatV alue*floatValue;System.out.println("the values are:");System.out.println("布尔类型变量flag="+flag);System.out.println("字符型变量yesChar="+yesChar);System.out.println("字节型变量finByte="+finByte);System.out.println("整型变量intValue="+intValue);System.out.println("长整型变量longValue="+longValue);System.out.println("短整型变量shortValue="+shortValue);System.out.println("浮点型变量floatValue="+floatValue);System.out.println("双精度浮点型变量doubleValue="+doubleValue); }//end main()}//习题2.9import java.util.*;class PubTest1{private int ivar1;private float fvar1,fvar2;public PubTest1(){fvar2=0.0f;}public float sum_f_I(){fvar2=fvar1+ivar1;return fvar2;}public void print(){System.out.println("fvar2="+fvar2);}public void setIvar1(int ivalue){ivar1=ivalue;}public void setFvar1(float ivalue){fvar1=ivalue;}}public class PubMainTest {public static void main(String[] args) {PubTest1 pubt1=new PubTest1();pubt1.setIvar1(10);pubt1.setFvar1(100.02f);pubt1.sum_f_I();pubt1.print();}}//习题2.10import java.util.*;class Date {private int year;private int month;private int day;public Date(int day, int month, int year) { //构造函数,构造方法this.year = year;this.month = month;this.day = day;} //end public MyDate(int y,int m,int d)public int getYear() { //返回年return year;} //end getYear()public int getMonth() { //返回月return month;} //end getMonth()public int getDay() { //返回日return day;} //end getDay()} //end class Datepublic class Teacher {String name;//教师名字boolean sex;//性别,true表示男性Date birth;//出生日期String salaryID;//工资号String depart;//教师所在系所String posit;//教师职称String getName() {return name;}void setName(String name) { = name;}boolean getSex() {return sex;}void setSex(boolean sex) {this.sex = sex;}Date getBirth() {return birth;}void setBirth(Date birth) {this.birth = birth;}String getSalaryID() {return salaryID;}void setSalaryID(String salaryID) {this.salaryID = salaryID;}String getDepart() {return depart;}void setDepart(String depart) {this.depart = depart;}String getPosit() {return posit;}void setPosit(String posit) {this.posit = posit;}public Teacher(){System.out.println("父类无参数的构造方法!!!!!!!"); }//如果这里不加上这个无参数的构造方法将会出错!!!!public Teacher(String name,boolean sex,Date birth,String salaryid,String depart,String posit){ =name;this.sex=sex;this.birth=birth;this.salaryID=salaryid;this.depart=depart;this.posit=posit;}//end Teacher()public void print(){System.out.print("the teacher'name:");System.out.println(this.getName());System.out.print("the teacher'sex:");if(this.getSex()==false){System.out.println("女");}else{System.out.println("男");}System.out.print("the teacher'birth:");System.out.println(this.getBirth().getYear()+"-"+this.getBirth().getMonth()+"-"+this.getBirth().getDay()); System.out.print("the teacher'salaryid:");System.out.println(this.getSalaryID());System.out.print("the teacher'posit:");System.out.println(this.getPosit());System.out.print("the teacher'depart:");System.out.println(this.getDepart());}//end print()public static void main(String[] args) {Date dt1=new Date(11,23,1989);Date dt2=new Date(2,6,1975);Date dt3=new Date(11,8,1964);Date dt4=new Date(10,4,1975);Date dt5=new Date(8,9,1969);//创建各系教师实例,用来测试Teacher t1=new Teacher("王莹",false,dt1,"123","经济学","prefessor");ResearchTeacher rt=new ResearchTeacher("杨zi青",true,dt2,"421","软件工程","associate prefessor","software");LabTeacher lat=new LabTeacher("王夏瑾",false,dt3,"163","外语","pinstrucor","speech lab");LibTeacher lit=new LibTeacher("马二孩",true,dt4,"521","大学物理","prefessor","physicalLib");AdminTeacher at=new AdminTeacher("王xi",false,dt5,"663","环境","prefessor","dean");/////////分别调用各自的输出方法,输出相应信息////////////////////////////System.out.println("-------------------------------");t1.print();//普通教师信息System.out.println("-------------------------------");rt.print();//研究系列教师信息System.out.println("-------------------------------");lat.print();//普通教师信息System.out.println("-------------------------------");lit.print();//实验系列教师信息System.out.println("-------------------------------");at.print();//行政系列教师信息System.out.println("-------------------------------");}//end main()}//end public class Teacherclass ResearchTeacher extends Teacher{private String resField;public ResearchTeacher(String name, boolean sex, Date birth, String salaryid,String depart, String posit, String resField) { = name;this.sex = sex;this.birth = birth;this.salaryID = salaryid;this.depart = depart;this.posit = posit;this.resField = resField;} //end public ResearchTeacher(){}String getResField(){return resField;}void setResField(String resField){this.resField=resField;}public void print() {System.out.print("research teacher info is:");System.out.print("the teacher'name:");System.out.println(this.getName());System.out.print("the teacher'sex:");if (this.getSex() == false) {System.out.println("女");}else {System.out.println("男");}System.out.print("the teacher'birth:");System.out.println(this.getBirth().getYear() + "-" +this.getBirth().getMonth() + "-" +this.getBirth().getDay());System.out.print("the teacher'salaryid:");System.out.println(this.getSalaryID());System.out.print("the teacher'posit:");System.out.println(this.getPosit());System.out.print("the teacher'depart:");System.out.println(this.getDepart());System.out.print("the teacher'resField:");System.out.println(this.getResField());} //end print()}//end class ResearchTeacherclass LabTeacher extends Teacher{private String labName;public LabTeacher(String name, boolean sex, Date birth,String salaryid, String depart,String posit, String labName) { = name;this.sex = sex;this.birth = birth;this.salaryID = salaryid;this.depart = depart;this.posit = posit;bName = labName;} //end public ResearchTeacher(){}String getLabName(){return labName;}void setLabName(String labName){bName=labName;}public void print() {System.out.print("lab teacher info is:");System.out.print("the teacher'name:");System.out.println(this.getName());System.out.print("the teacher'sex:");if (this.getSex() == false) {System.out.println("女");}else {System.out.println("男");}System.out.print("the teacher'birth:");System.out.println(this.getBirth().getYear() + "-" +this.getBirth().getMonth() + "-" +this.getBirth().getDay());System.out.print("the teacher'salaryid:");System.out.println(this.getSalaryID());System.out.print("the teacher'posit:");System.out.println(this.getPosit());System.out.print("the teacher'depart:");System.out.println(this.getDepart());System.out.print("the teacher'labName:");System.out.println(bName);} //end print()}//end class LabTeacherclass LibTeacher extends Teacher{private String libName;public LibTeacher(String name,boolean sex,Date birth,String salaryid,String depart,String posit,String libName){ = name;this.sex = sex;this.birth = birth;this.salaryID = salaryid;this.depart = depart;this.posit = posit;this.libName=libName;}//end public ResearchTeacher(){}String getLibName(){return libName;}void setLibName(String libName){this.libName=libName;}public void print() {System.out.print("lib teacher info is:");System.out.print("the teacher'name:");System.out.println(this.getName());System.out.print("the teacher'sex:");if (this.getSex() == false) {System.out.println("女");}else {System.out.println("男");}System.out.print("the teacher'birth:");System.out.println(this.getBirth().getYear() + "-" +this.getBirth().getMonth() + "-" +this.getBirth().getDay());System.out.print("the teacher'salaryid:");System.out.println(this.getSalaryID());System.out.print("the teacher'posit:");System.out.println(this.getPosit());System.out.print("the teacher'depart:");System.out.println(this.getDepart());System.out.print("the teacher'libName:");System.out.println(this.libName);} //end print()}//end class LibTeacherclass AdminTeacher extends Teacher{private String managePos;public AdminTeacher(String name,boolean sex,Date birth,String salaryid,String depart,String posit,String managePos){ = name;this.sex = sex;this.birth = birth;this.salaryID = salaryid;this.depart = depart;this.posit = posit;this.managePos=managePos;}//end public ResearchTeacher(){}String getManagePos(){return managePos;}void setManagePos(String managePos){this.managePos=managePos;}public void print() {System.out.print("adminteacher info is:");System.out.print("the teacher'name:");System.out.println(this.getName());System.out.print("the teacher'sex:");if (this.getSex() == false) {System.out.println("女");}else {System.out.println("男");}System.out.print("the teacher'birth:");System.out.println(this.getBirth().getYear() + "-" +this.getBirth().getMonth() + "-" +this.getBirth().getDay());System.out.print("the teacher'salaryid:");System.out.println(this.getSalaryID());System.out.print("the teacher'posit:");System.out.println(this.getPosit());System.out.print("the teacher'depart:");System.out.println(this.getDepart());System.out.print("the teacher'managePos:");System.out.println(this.managePos);} //end print()}//end class AdminTeacher习题2.11public class Course {private String courseID;private String courseName;private String courseType;private int classHour;private float credit;public Course(String courseID, String courseName, String courseType,int classHour, float credit) {this.courseID=courseID;this.courseName=courseName;this.courseType=courseType;this.classHour=classHour;this.credit=credit;}//end public Course(){}String getID() {return courseID;}void setID(String id) {this.courseID = id;}String getName() {return courseName;}void setName(String name) {this.courseName = name;}String getType() {return courseType;}void setType(String type) {this.courseType = type;}int getClassHour() {return classHour;}void setClassHour(int hour) {this.classHour = hour;}float getCredit() {return classHour;}void setCredit(float credit) {this.credit= credit;}public void print(){System.out.println("the basic info of this course as followed:");System.out.println("courseID="+this.getID());System.out.println("courseName="+this.getName());System.out.println("courseType="+this.getType());System.out.println("classHour="+this.getClassHour());System.out.println("credit="+this.getCredit());}public static void main(String[] args) {Course cs=new Course("d12","java程序设计(第二版)","cs",64,3.0f);System.out.println("----------------------------------");cs.print();System.out.println("修改课程学分为4.0f");cs.setCredit(4);cs.print();}}//习题2.12public class MyGraphic {String lineColor;String fillColor;MyGraphic(String lc,String fc){this.lineColor=lc;this.fillColor=fc;}void print(){System.out.println("line color is "+this.lineColor+"\t fill color is "+this.fillColor);}public static void main(String[] args) {float rd=(float)4.5;MyCircle mc=new MyCircle(rd,"black","white");MyRectangle mr=new MyRectangle(4,6,"red","blue");System.out.println("Circle info ");mc.print();System.out.println("circumference is " + mc.calCircum());System.out.println("square is " + mc.calSquare());System.out.println("rectangle info: ");mr.print();System.out.println("circumference is " + mr.calCircum());System.out.println("square is " + mr.calSquare());}//end main(){}}//end public class MyGraphicclass MyRectangle extends MyGraphic{float rLong;float rWidth;MyRectangle (float rl,float rw,String lc,String fc){super(lc,fc);this.rLong=rl;this.rWidth=rw;}//end MyRectangle (){}float calCircum(){return ((float)((this.rLong+this.rWidth)*2));}float calSquare(){return ((float)(this.rLong*this.rWidth));}}//end class MyRectangleclass MyCircle extends MyGraphic{float radius;MyCircle (float rd,String lc,String fc){super(lc,fc);this.radius=rd;}//end MyRectangle (){}float calCircum(){return (float)((this.radius*3.12*2));}float calSquare(){return ((float)(this.radius*this.radius*3.14));}}//end class MyCircle//习题2.13public class Vehicle {String brand;String color;int price;int number;public Vehicle(String b, String c) {this.brand = b;this.color = c;}public Vehicle(String b, String c, int p, int n) {this(b, c);this.price = p;this.number = n;}void print() {System.out.println("\n-------------------------");System.out.println("the vehicle info as followed :");System.out.println("brand=" + this.brand + "\t");System.out.println("color=" + this.color + "\t");System.out.println("price=" + this.price + "\t");System.out.println("number=" + this.number + "\t"); } //end void print()public static void main(String[] args) {V ehicle c1=new Vehicle("vehicle1","white");V ehicle c2=new Vehicle("vehicle2","white",300,1);Car cr=new Car("car1","red",300,4,400);Truck tk2=new Truck("truck1","black",300,400);c1.print();c2.print();cr.print();tk2.print();} //end main()} //end public class Vehicleclass Car extends Vehicle{int speed;Car(String b, String c, int p, int n,int s){super(b,c,p,n);this.speed=s;}void print(){super.print();System.out.print("speed="+this.speed); }}//end class Carclass Truck extends Vehicle{int speed;int weight;Truck(String b, String c, int s,int w){super(b,c);this.speed=s;this.weight=w;}void print(){super.print();System.out.print("speed="+this.speed);System.out.print("weight="+this.weight); }}//end class Truck//习题3.3public class Test {public static void main(String[] args) {int b1=1;int b2=1;System.out.println("b1=" + b1);System.out.println("b2=" + b2);b1<<=31;b2<<=31;System.out.println("b1=" + b1);System.out.println("b2=" + b2);b1 >>= 31;System.out.println("b1=" + b1);b1 >>= 1;System.out.println("b1=" + b1);b2 >>>= 31;System.out.println("b2=" + b2);b2 >>>= 1;System.out.println("b2=" + b2);}}//习题3.4public class Factorial {private int result,initVal;public static int Factorial(int n){if(n==0){return 1;}return n*Factorial(n-1);}public void print(){System.out.println(initVal+"!="+result); }public void setInitVal(int n){initVal=n;}public static void main(String[] args) {Factorial ff=new Factorial();for(int i=0;i<=4;i++){ff.setInitVal(2*(i+1));ff.result=Factorial(ff.initVal);ff.print();}//end for()}//end main()}//end public class Factorialpublic class Factorial2 {private int result,initVal;public void print(){System.out.println(initVal+"!="+result);}public void setInitVal(int n){initVal=n;}public static void main(String[] args) {Factorial2 ff=new Factorial2();for(int i=0;i<=4;i++){ff.setInitVal(2*(i+1));ff.result=1;for(int j=2;j<=ff.initV al;j++){ff.result*=j;}ff.print();}//end for()}//end main()}//习题3.5public class MathRandomTest {public static void main(String[] args) {int count=0,MAXof100,MINof100;int num,i;MAXof100=(int)(100*Math.random());MINof100=(int)(100*Math.random());System.out.print(MAXof100+" ");System.out.print(MINof100+" ");if(MAXof100>50)count++;if(MINof100>50)count++;if( MAXof100<MINof100){num=MINof100;MINof100=MAXof100;MAXof100=num;}//end if()for(i=0;i<98;i++){num=(int)(100*Math.random());System.out.print(num+((i+2)%10==9?"\n":" "));if(num>MAXof100){MAXof100=num;}else if(num<MINof100){MINof100=num;}if(num>50){count++;}}//end for()System.out.println("the max of 100 random integers is "+MAXof100);System.out.println("the min of 100 random integers is "+MINof100);System.out.println("the number of random more than50 is "+count); }//end main()}//end public class MathRandomTest//习题3.7public class PrintAst {public void printAstar() {System.out.print("*");}public void printSpace() {System.out.print(" ");}public static void main(String[] args) {PrintAst pa = new PrintAst();int initNum = 13;for (int i = 1; i <= initNum / 2 + 1; i++) {for (int n = 1; n <= i; n++) {pa.printSpace();pa.printSpace();}for (int m = 1; m <= initNum - 2 * i + 2; m++) {pa.printSpace();pa.printAstar();}System.out.println();} //end forif (initNum % 2 == 0) {for (int i = 1; i <= initNum / 2; i++) {pa.printSpace();pa.printSpace();}pa.printSpace();pa.printAstar();pa.printSpace();pa.printAstar();System.out.println();}for (int i = initNum / 2 + 2; i <= initNum; i++) {for (int n = 1; n <= initNum - i + 1; n++) {pa.printSpace();pa.printSpace();}for (int m = 1; m <= 2 * i - initNum; m++) {pa.printSpace();pa.printAstar();}System.out.println();} //end forSystem.out.println();} //end main()} //end public class PrintAst//习题3.8public class PrintTriag {public void printAstar() {System.out.print("*");}public static void main(String[] args) {int initLine = 10;int initNum = 10;PrintTriag pt = new PrintTriag();for (int i = 0; i < initLine; i++) {for (int j = 0; j < initNum - i; j++) {pt.printAstar();}System.out.println();}}//end main()}//end public class PrintTriag习题3.9import java.util.*;public class MultipleTable {public void printFormula(int i,int j,int res){System.out.print(i+"*"+j+"="+res+" "); }public static void main(String[] args) {MultipleTable mt=new MultipleTable();int initNum=9;int res=0;for(int i=1;i<=initNum;i++){for(int j=1;j<=i;j++){res=i*j;mt.printFormula(i,j,res);}System.out.println();}//end for}//end main()}//end public class MultipleTable习题3.10import java.io.*;public class HuiWen {boolean isHuiWen(char str[], int n) {int net = 0;int i, j;for (i = 0, j = n - 1; i < n / 2; i++, j--) {if (str[i] == str[j]) {net++;} //end if} //end forif (net == (int) (n / 2)) {return true;} //end ifelse {return false;}} //end boolean isHuiWen(char str[], int n)public static void main(String[] args) {HuiWen hw1 = new HuiWen();String pm = "";try {InputStreamReader reader = new InputStreamReader(System.in);BufferedReader input = new BufferedReader(reader);System.out.print("give your test string:\n");pm = input.readLine();System.out.println(pm);} //end trycatch (IOException e) {System.out.print(e);} //end catchboolean bw = hw1.isHuiWen(pm.toCharArray(), pm.length());if (bw == true) {System.out.println("是回文");}else {System.out.println("不是回文");}} //end main()} //end public class HuiWenimport java.io.*;public class HuiWen2 {String reverse(String w1){String w2;char[]str1=w1.toCharArray();int len=w1.length();char[]str2=new char[len];for(int i=0;i<len;i++){str2[i]=str1[len-1-i];}w2=new String(str2);return w2;}public static void main(String[] args) {HuiWen2 hw1 = new HuiWen2();String pm = "";try {InputStreamReader reader = new InputStreamReader(System.in);BufferedReader input = new BufferedReader(reader);System.out.print("give your test string:\n");pm = input.readLine();} //end trycatch (IOException e) {System.out.print(e);} //end catchString w2=hw1.reverse(pm);if(pareTo(pm)==0){System.out.println("是回文");}else {System.out.println("不是回文");}}}//习题3.11import java.io.*;public class PrimeNumber {private int pm;public void setPm(int pm){this.pm=pm;}public boolean isPrime(){boolean bl=true;int i=2;for(i=2;i<=Math.sqrt(pm);){if(pm%i==0){bl=false;break;}else{i++;}}//end forreturn bl;}//end public boolean isPrime()public static void main(String[] args) {PrimeNumber prim=new PrimeNumber();int testNum=0;try{InputStreamReader reader = new InputStreamReader(System.in);BufferedReader input = new BufferedReader(reader);System.out.print("give your test number:\n");testNum=Integer.parseInt(input.readLine());}//end trycatch(IOException e){System.out.println(e);}//end catchprim.setPm(testNum);boolean bl=prim.isPrime();if(bl==true){System.out.println(testNum+"是质数");}else {System.out.println(testNum+"不是质数");}}//end main}//end public class PrimeNumber习题3.12import java.io.*;public class Tempconverter {double celsius(double y){return ((y-32)/9*5);}public static void main(String[] args) {Tempconverter tc=new Tempconverter ();double tmp=0;try{InputStreamReader reader = new InputStreamReader(System.in);BufferedReader input = new BufferedReader(reader);System.out.print("give your fahrenheit number:\n");tmp=Double.parseDouble(input.readLine());}//end trycatch(NumberFormatException e){System.out.println(e);}//end catchcatch(IOException e){System.out.println(e);}//end catchSystem.out.println("the celsius of temperature is "+tc.celsius(tmp));}//end main()}//end public class Tempconverter习题3.13import java.io.*;public class Trigsquare {double x, y, z;Trigsquare(double x, double y, double z) {this.x = x;this.y = y;this.z = z;}boolean isTriangle() {boolean bl = false;if (this.x > 0 && this.y > 0 && this.z > 0) {if ( (this.x + this.y) > this.z && (this.x + this.z) > this.y && (this.z + this.y) > this.x) {bl = true;} //ebd ifelse {bl = false;} //end else} //end if(this.x>0&&this.y>0&&this.z>0)return bl;} //end boolean isTriangle()double getArea() {double s = (this.x + this.y + this.z) / 2.0;return (Math.sqrt(s * (s - this.x) * (s - this.y) * (s - this.z)));} //end double getArea()public static void main(String[] args) {double s[] = new double[3];try {InputStreamReader reader = new InputStreamReader(System.in);BufferedReader input = new BufferedReader(reader);System.out.print("输入三角形的三边的长度:\n");。
java语言程序设计基础篇第8版课后答案【篇一:java语言程序设计基础篇第八章第十题编程参考答案】icequation的类。
这个类包括:代表三个系数的私有数据域a、b、c。
一个参数为a、b、c的构造方法。
a、b、c的三个get方法。
一个名为getdiscriminant()的方法返回判别式,b2-4ac。
一个名为getroot1()和getroot2()的方法返回等式的两个根。
这些方法只有在判别式为非负数时才有用。
如果判别式为负,方法返回0。
画出该类的uml图。
实现这个类。
编写一个测试程序,提示用户输入a、b、c的值,然后显示判别式的结果。
如果判别式为正数,显示两个根;如果判别式为0,显示一个根;否则,显示“the equation has no roots”。
代码:class quadraticequation{private int a,b,c;quadraticequation(){}public quadraticequation(int a,int b,int c){this.a=a;this.b=b;this.c=c;}public int geta(){return a;}public int getb(){return b;}public int getc(){return c;}public int getdiscriminant(){if(b*b-4*a*c=0)return b*b-4*a*c;elsereturn 0;}public int getroot1(){if(b*b-4*a*c=0)return (int)((-b+math.pow(b*b-4*a*c, 0.5))/(2*a));elsereturn 0;}public int getroot2(){if(b*b-4*a*c=0)elsereturn 0;}}public class xiti810 {public static void main(string[] args){system.out.println(请输入要计算的方程的系数a、b和c:);java.util.scanner input =newjava.util.scanner(system.in);system.out.print(a=);int a=input.nextint();system.out.print(b=);int b=input.nextint();system.out.print(c=);int c=input.nextint();quadraticequation q=new quadraticequation(a,b,c);q.getdiscriminant();if(q.getdiscriminant()0)system.out.println(它们的根为:+q.getroot1()+和+q.getroot2()); else if(q.getdiscriminant()==0)system.out.println(此方程只有一个根为:+q.getroot1());elsesystem.out.println(方程无解);}}【篇二:java语言程序设计(第8版)第5章完整答案programming exercises(程序练习题)答案完整版】class exercise01 {public static void main(string[] args) {final int pentagonal_numbers_per_line = 10;final int pentagonal_numbers_to_print = 100;int count = 1;int n = 1;while (count = pentagonal_numbers_to_print) {int pentagonalnumber = getpentagonalnumber(n);n++;if (count % pentagonal_numbers_per_line == 0)system.out.printf(%-7d\n, pentagonalnumber);elsesystem.out.printf(%-7d, pentagonalnumber);count++;}}public static int getpentagonalnumber(int n) {return n * (3 * n - 1) / 2;}}5_2import java.util.scanner;public class exercise02 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an interger: );long number = input.nextlong();system.out.println(the sum of the digits in + number + is + sumdigits(number)); }public static int sumdigits(long n) {int sum = 0;long remainingn = n;}} do { long digit = remainingn % 10; remainingn = remainingn / 10; sum += digit; } while (remainingn != 0); return sum;第03题import java.util.scanner;public class exercise03 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an integer: );int number = input.nextint();//display resultsystem.out.println(is + number + a palindrome? + ispalindrome(number)); }public static boolean ispalindrome(int number) {if (number == reverse(number))return true;elsereturn false;}public static int reverse(int number) {int reversenumber = 0;do {int digit = number % 10;number = number / 10;reversenumber = reversenumber * 10 + digit;} while (number != 0);return reversenumber;}第04题import java.util.scanner;public class exercise04 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an integer: );int number = input.nextint();//display resultsystem.out.print(the reversal of + number + is );reverse(number);}public static void reverse(int number) {int reversenumber = 0;do {int digit = number % 10;number = number / 10;reversenumber = reversenumber * 10 + digit;} while (number != 0);system.out.println(reversenumber);}}第05题import java.util.scanner;public class exercise05 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter three numberssystem.out.print(enter three numbers: );double num1 = input.nextdouble();}double num3 = input.nextdouble(); system.out.print(num1 + + num2 + + num3 + in increasing order: ); displaysortednumbers(num1, num2, num3); } public static void displaysortednumbers(double num1, double num2, double num3) { double max = math.max(math.max(num1,num2), num3); double min = math.min(math.min(num1, num2), num3); double second = 0; if (num1 != max num1 !=min)second = num1; if (num2 != max num2 != min)second = num2; if (num3 != max num3 != min)second = num3; system.out.println(min + + second + + max); }5.6import java.util.scanner;public class exercise06 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an integer: );int number = input.nextint();displaypattern(number);}public static void displaypattern(int n) {int i;int j;for (i = 1; i = n; i++) {for (j = 0; j n - i; j++)system.out.print( );}} for (j = 0; j = i - 1; j++) system.out.printf(%-5d, i - j); system.out.println(); }5.7import java.util.scanner;public class exercise07 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter investment amountsystem.out.print(enter the investment amount: );double investmentamount = input.nextdouble();//prompt the user to enter interest ratesystem.out.print(enter the annual interest rate: );double annualinterestrate = input.nextdouble();//prompt the user to enter yearssystem.out.print(enter number of years: );int years = input.nextint();system.out.println(\nthe amount invested: + investmentamount);system.out.println(annual interest rate: + annualinterestrate + %);system.out.println(years\tfuture value);for (int i = 1; i = years; i++) {system.out.print(i + \t);system.out.printf(%10.2f\n,futureinvestmentvalue(investmentamount, annualinterestrate / 1200, i));}}public static double futureinvestmentvalue(double investmentamount, double monthinterestrate, int years) {return investmentamount * math.pow(1 + monthinterestrate, years * 12);}}【篇三:java语言程序设计基础篇前三章课后习题】s=txt>1.1(显示三条消息)编写程序,显示welcome to java、welcome to computer science和programming is fun。
Java程序设计实用教程(第4版)习题解答与实验指导叶核亚编著2013年11月目录“Java程序设计”课程教学要求 (1)第1章Java概述 (3)第2章Java语言基础 (5)第3章类的封装、继承和多态 (22)第4章接口、内部类和Java API基础 (37)第5章异常处理 (42)第6章图形用户界面 (44)第7章多线程 (49)第8章输入/输出流和文件操作 (51)“Java程序设计”课程教学要求1. 课程性质、目的和任务程序设计是高等学校计算机学科及电子信息学科各专业本科的核心专业基础课程,是培养学生软件设计能力的重要课程。
在计算机学科的本科教学中,起着非常重要的作用。
“Java程序设计”是计算机科学与技术专业本科的专业基础限选课,开设本课程的目的是:进行程序设计和面向对象方法的基础训练;使用Java编程技术,设计解决操作系统、网络通信、数据库等多种实际问题的应用程序。
本课程通过全面、系统地介绍Java语言的基础知识、运行机制、多种编程方法和技术,使学生理解和掌握面向对象的程序设计方法,理解和掌握网络程序的特点和设计方法,建立起牢固扎实的理论基础,培养综合应用程序的设计能力。
本课程的先修课程包括:C/C++程序设计I、C/C++程序设计II、数据结构、操作系统、计算机网络、数据库原理等。
2. 教学基本要求本课程的基本要求如下。
①了解Java语言特点,理解Java Application应用程序的运行原理和方法。
掌握在JDK 环境中编译和运行程序的操作,熟悉在MyEclipse集成开发环境中,编辑、编译、运行和调试程序的操作。
②掌握Java语言中语句、数组、引用类型等基本语法成分的使用方法,通过类、接口、内嵌类型、包、异常处理等机制表达和实现面向对象程序设计思想。
③掌握Java的多种实用技术,包括图形用户界面、多线程、文件操作和流、使用URL 和Socket进行网络通信等。
④熟悉Java JDBC数据库应用的设计方法。
Java程序设计实用教程(第4版)习题解答与实验指导叶核亚编著2013年11月目录“Java程序设计”课程教学要求 (1)第1章Java概述 (3)第2章Java语言基础 (5)第3章类的封装、继承和多态 (22)第4章接口、内部类和Java API基础 (38)第5章异常处理 (43)第6章图形用户界面 (45)第7章多线程 (50)第8章输入/输出流和文件操作 (52)“Java程序设计”课程教学要求1. 课程性质、目的和任务程序设计是高等学校计算机学科及电子信息学科各专业本科的核心专业基础课程,是培养学生软件设计能力的重要课程。
在计算机学科的本科教学中,起着非常重要的作用。
“Java程序设计”是计算机科学与技术专业本科的专业基础限选课,开设本课程的目的是:进行程序设计和面向对象方法的基础训练;使用Java编程技术,设计解决操作系统、网络通信、数据库等多种实际问题的应用程序。
本课程通过全面、系统地介绍Java语言的基础知识、运行机制、多种编程方法和技术,使学生理解和掌握面向对象的程序设计方法,理解和掌握网络程序的特点和设计方法,建立起牢固扎实的理论基础,培养综合应用程序的设计能力。
本课程的先修课程包括:C/C++程序设计I、C/C++程序设计II、数据结构、操作系统、计算机网络、数据库原理等。
2. 教学基本要求本课程的基本要求如下。
①了解Java语言特点,理解Java Application应用程序的运行原理和方法。
掌握在JDK 环境中编译和运行程序的操作,熟悉在MyEclipse集成开发环境中,编辑、编译、运行和调试程序的操作。
②掌握Java语言中语句、数组、引用类型等基本语法成分的使用方法,通过类、接口、内嵌类型、包、异常处理等机制表达和实现面向对象程序设计思想。
③掌握Java的多种实用技术,包括图形用户界面、多线程、文件操作和流、使用URL 和Socket进行网络通信等。
④熟悉Java JDBC数据库应用的设计方法。
《JAVA 程序设计基础》课程标准一、课程概述本门课程是为计算机科学专业的软件工程方向、软件服务外包方向、网络技术方向,以及通信工程专业的通信工程方向、嵌入式系统方向开设的一门专业基础课。
其主要内容有Java 基本语法、Java 基本语句、面向对象程序设计、多线程技术、异常处理机制、Windows 环境编程、Java 网络编程等等,其目标是为大学本科高年级学生提供有关Java 的基础知识以及面向对象的程序设计方法所必需具有的知识和技能;Java 语言的运行环境有许多特性,对图形用户界面(GUIs)、多线程和网络的支持,是当今应用最广的一门网络语言。
本门课程是计算机科学技术与通讯技术类专业的应用学科,本门课程的先修课程是《数据结构》,后续课程有《Java Swing 图形界面设计》、《JAVA 模式设计》。
该课程可以在大学二年级开设。
二、课程目标完成本课程的学习后,学生应该能够:1.了解Java 语言的主要特性,并理解面向对象的编程技术;2.掌握Java 语言的运行环境和Java 的基本语句及编程;3.理解并学会使用异常处理机制和多媒体技术;4.掌握图形用户界面设计和事件处理机制;5.学会开发多线程Java 应用程序和Java applets 小应用程序;6.理解TCP/IP和用户数据报协议(UDP),并掌握Java 网络编程和数据库编程。
三、课程内容与教学要求这门学科的知识与技能要求分为知道、理解、掌握、学会四个层次。
这四个层次的一般涵义表述如下:知道——是指对本门课程的教学内容和教学标准的认知。
理解——是指对本门课程涉及到的概念、原理与技术能明白和解释。
掌握——是指能运用已理解的知识进行编程。
学会——是指能灵活运用相关知识进行实验分析与设计。
教学内容和要求表中的“√”号表示教学知识和技能的教学要求层次。
本标准中打“*”号的内容可作为自学,教师可根据实际情况确定要求或不布置要求。
教学内容及教学要求表四、课程实施JAVA 语言程序设计是计算机科学技术以及通讯技术类选修课;一般情况下,每周安排3 课时,共54 课时,其中讲授 40 课时、实验 14 课时。
Chapter 8 Objects and Classes1. See the section "Defining Classes for Objects."2. The syntax to define a class ispublic class ClassName {}3.The syntax to declare a reference variable for anobject isClassName v;4.The syntax to create an object isnew ClassName();5. Constructors are special kinds of methods that arecalled when creating an object using the new operator.Constructors do not have a return type—not even void.6. A class has a default constructor only if the classdoes not define any constructor.7. The member access operator is used to access a datafield or invoke a method from an object.8.An anonymous object is the one that does not have areference variable referencing it.9.A NullPointerException occurs when a null referencevariable is used to access the members of an object.10.An array is an object. The default value for theelements of an array is 0 for numeric, false for boolean,‘\u0000’ for char, null for object element type.11.(a) There is such constructor ShowErrors(int) in theShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors(5);}public ShowErrors () {}}On Line 3, new ShowErrors(5) attempts to create aninstance using a constructor ShowErrors(int), but theShowErrors class does not have such a constructor. That is an error.(b) x() is not a method in the ShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors();t.x();}public ShowErrors () {}}On Line 4, t.x() is invoked, but the ShowErrors classdoes not have the method named x(). That is an error.(c) The program compiles fine, but it has a runtimeerror because variable c is null when the printlnstatement is executed.(d) new C(5.0) does not match any constructors in classC. The program has a compilation error because class Cdoes not have a constructor with a double argument. 12.The program does not compile because new A() is used inclass Test, but class A does not have a defaultconstructor. See the second NOTE in the Section,“Constructors.”13.falsee the Date’s no-arg constructor to create a Date forthe current time. Use the Date’s toString() method todisplay a string representation for the Date.e the JFrame’s no-arg constructor to create JFrame.Use the setTitle(String) method a set a title and use thesetVisible(true) method to display the frame.16.Date is in java.util. JFrame and JOptionPane are injavax.swing. System and Math are in ng.17. System.out.println(f.i);Answer: CorrectSystem.out.println(f.s);Answer: Correctf.imethod();Answer: Correctf.smethod();Answer: CorrectSystem.out.println(F.i);Answer: IncorrectSystem.out.println(F.s);Answer: CorrectF.imethod();Answer: IncorrectF.smethod();Answer: Correct18. Add static in the main method and in the factorialmethod because these two methods don’t need referenceany instance objects or invoke any instance methods inthe Test class.19. You cannot invoke an instance method or reference aninstance variable from a static method. You can invoke astatic method or reference a static variable from aninstance method? c is an instance variable, which cannot be accessed from the static context in method2.20. Accessor method is for retrieving private data value and mutator method is for changing private data value. The naming convention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. The naming convention for mutator method is setDataFieldName(value).21.Two benefits: (1) for protecting data and (2) for easyto maintain the class.22. Not a problem. Though radius is private,myCircle.radius is used inside the Circle class. Thus, it is fine.23. Java uses “pass by value” to pass parameters to amethod. When passing a variable of a primitive type toa method, the variable remains unchanged after themethod finishes. However, when passing a variable of areference type to a method, any changes to the objectreferenced by the variable inside the method arepermanent changes to the object referenced by thevariable outside of the method. Both the actualparameter and the formal parameter variables referenceto the same object.The output of the program is as follows:count 101times 024.Remark: The reference value of circle1 is passed to x andthe reference value of circle2 is passed to y. The contents ofthe objects are not swapped in the swap1 method. circle1 andcircle2 are not swapped. To actually swap the contents of these objects, replace the following three linesCircle temp = x;x =y;y =temp;bydouble temp = x.radius;x.radius = y.radius;y.radius = temp;as in swap2.25. a. a[0] = 1 a[1] = 2b. a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1’s i = 2 t1’s j = 1t2’s i = 2 t2’s j = 126. (a) null(b) 1234567(c) 7654321(d) 123456727. (Line 4 prints null since dates[0] is null. Line 5 causes a NullPointerException since it invokes toString() method from the null reference.)。