Java语言程序设计 第2版 (郑莉)课后习题答案
java语言程序设计教程第二版习题解答
4) 消息:消息是对象之间进行通信的一种数据结构。
5) 封装:封装性是保证软件部件具有优良的模块性的基础。面向对象的类是封装良好
的模块,类定义将其说明(用户可见的外部接口)与实现(用户不可见的内部实现)
显式地分开,其内部实现按其具体定义的作用域提供保护。
End of j loop;i=2
(7)Java系统要求对对象进行相容性检查,以防止不安全的类型转换。
(8) Java语言最强大的特性之一是它的平台独立性,Java可以处理好平台之间的
移植问题。
(9)Java语言中没有全局变量的定义,只能通过公用的静态的变量实现,从而减少了
引起错误的地方。
6.什么叫Java虚拟机?什么叫Java的字节码?
(3)的运行结果如下:
运行结果取决于随机数。求随机数的阶乘,其中的一个运行结果如下:
3!=6
(4)的运行结果如下:
0 0 0
0 0 1
0 0 2
End of k loop;j=0
0 1 0
0 1 1
6.阅读下列程序,写出运行结果。
(1).
public class Example0401{
public static void main(String[] args){
for(int x=0;x<10;x++){
int y=x*x+x+41';
System.out.println("\t"+x+"\t"+y);
2 0 1
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));- 2 - staff[1]=new Employee("Carl Carcker",75000,new MyDate(1987,12,15)); staff[2]=new Employee("Tony T ester",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=floatValue*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)- 4 -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);- 6 -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 ResearchT eacher extends Teacher{private String resField;public ResearchT eacher(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 T eacher{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){- 8 -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 ResearchT eacher(){}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;- 10 -}//end public ResearchT eacher(){}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;}- 12 -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;- 14 -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) {Vehicle c1=new Vehicle("vehicle1","white");Vehicle 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 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){- 16 -}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.initVal;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(" ");}- 18 -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 MultipleT able {public void printFormula(int i,int j,int res){ System.out.print(i+"*"+j+"="+res+" "); }public static void main(String[] args) {MultipleT able mt=new MultipleT able();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()- 20 - }//end public class MultipleT able习题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 {- 22 -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");for (int i = 0; i <= 2; i++) { //输入三个数s[i] = Double.parseDouble(input.readLine());} //end for} //end trycatch (NumberFormatException e) {System.out.println("format error!!!");} //end catch- 24 - catch (IOException e) {System.out.print(e);} //end catchTrigsquare ts = new Trigsquare(s[0], s[1], s[2]);if (ts.isTriangle() == true) {System.out.println("三角形的面积是" + ts.getArea());} //end ifelse {System.out.println("输入的三边不能组成三角形!!");} //end else} //end main()} //end public class Trigsquare//习题3.14import java.util.*;import java.io.*;import java.util.Date;import java.text.*;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.GregorianCalendar.*;。
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));- 2 -staff[1]=new Employee("Carl Carcker",75000,new MyDate(1987,12,15)); staff[2]=new Employee("Tony T ester",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 MyTestClassimport java.util.*;public class DataType {public static void main(String[] args) {boolean flag;char yesChar;byte finByte;int intValue;long longValue;shortshortValue;float floatValue;double doubleValue;flag=true;yesChar='y';finByte=30;intValue=-7000;longValue=200l;shortValue=20000;floatValue=9.997E-5f;doubleValue=floatValue*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()}import 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();}}import 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;- 4 -} //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;}voidsetName(Stringname) { = 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()- 6 -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 ResearchT eacher extends Teacher{private String resField;public ResearchT eacher(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 T eacher{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() + "-" +- 8 - 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 ResearchT eacher(){}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;- 10 -this.sex = sex;this.birth = birth;this.salaryID = salaryid;this.depart = depart;this.posit = posit;this.managePos=managePos;}//end public ResearchT eacher(){}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 AdminTeacherpublic 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;}- 12 -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();} }public 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));}- 14 - }//end class MyCirclepublic 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) {Vehicle c1=new Vehicle("vehicle1","white");Vehicle 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 Truckpublic 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);- 16 -b2 >>>= 1;System.out.println("b2=" + b2);} }public 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 voidmain(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.initVal;j++){ff.result*=j;}ff.print();}//end for()}//end main()}public 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);- 18 - }//end main() }//end public class MathRandomTestpublic 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 PrintAstpublic 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 PrintTriagimport java.util.*;public class MultipleT able {public void printFormula(int i,int j,int res){System.out.print(i+"*"+j+"="+res+" ");- 20 -public static void main(String[] args) {MultipleT able mt=new MultipleT able();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 MultipleT ableimport 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);- 22 -} //end catchString w2=hw1.reverse(pm);if(pareTo(pm)==0){System.out.println("是回文");}else {System.out.println("不是回文");}} }import 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 PrimeNumberimport 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 Tempconverterimport java.io.*;public class Trigsquare {double x, y, z;- 24 -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");for (int i = 0; i <= 2; i++) { //输入三个数s[i] = Double.parseDouble(input.readLine());} //end for} //end trycatch (NumberFormatException e) {System.out.println("format error");} //end catchcatch (IOException e) {System.out.print(e);} //end catch。
Java语言程序设计(郑莉)第七章课后习题答案
Java语言程序设计第七章课后习题答案1.数组的声明与数组元素的创建有什么关系?答:声明数组仅仅是代表试图创建数组,不分配任何存储空间,声明是为创建做“铺垫”。
2.Vector类的对象与数组有什么关系?什么时候适合使用数组,什么时候适合使用Vector?答:vector是一个能够存放任意对象类型的动态数组,容量能自动扩充,而数组存储固定且类型相同的对象;对于存储固定类型相同的对象使用数组,对于存储不同类型或者动态调整数组大小的情况使用Vector。
3.与顺序查找相比,二分查找有什么优势?使用二分查找的条件?答:对于大数据量中进行查找时二分查找比顺序查找效率高得多;条件是已排序的数组。
4.试举出三种常见的排序算法,并简单说明其排序思路。
答:①选择排序:基本思想是站在未排序列中选一个最小元素,作为已排序子序列,然后再重复地从未排序子序列中选取一个最小元素,把它加到已经排序的序列中,作为已排序子序列的最后一个元素,直到把未排序列中的元素处理完为止。
②插入排序:是将待排序的数据按一定的规则逐一插入到已排序序列中的合适位置处,直到将全部数据都插入为止。
③二分查找:将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
5.声明一个类People,成员变量有姓名、出生日期、性别、身高、体重等;生成10个People 类对象,并放在一个以为数组中,编写方法按身高进行排序。
//People类public class People{private String name;private String birthdaydate;private String sex;private double height;private double weight;public People(){//默认构造函数}public People(People p){=;this.birthdaydate=p.birthdaydate;this.sex=p.sex;this.height=p.height;this.weight=p.weight;}public People(String name,String birthdaydate,String sex,double height,double weight){=name;this.birthdaydate=birthdaydate;this.sex=sex;this.height=height;this.weight=weight;}public String getName() {return name;}public void setName(String name) { = name;}public String getBirthdaydate() {return birthdaydate;}public void setBirthdaydate(String birthdaydate) {this.birthdaydate = birthdaydate;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public String toString(){return"姓名:"+name+"\n出生年月:"+birthdaydate+"\n性别:"+sex+"\n 身高:"+height+"\n体重:"+weight;}}//test7_5类public class test7_5 {/***@param args*/public static void main(String[] args) {// TODO Auto-generated method stubPeople[] people={new People("林楚金","1989年8月13日","男",182,63.5),new People("诸葛亮","181年7月23日","男",184,76.6),new People("迈克杰克逊","1958年8月29日","男",180,60),new People("乔丹","1963年2月17日","男",198,98.1),new People("拿破仑","1769年8月15日","男",159.5,63),new People("苍井空","1983年11月11日","女",155,45),};People temp=new People();for(int i=0;i<people.length-1;i++)for(int j=i+1;j<people.length;j++){if(people[i].getHeight()<people[j].getHeight()){temp=people[j];people[j]=people[i];people[i]=temp;}}System.out.println("按身高从小到大排序后的结果如下:");for(int i=0;i<people.length;i++)System.out.println(people[i]+"\n");}}运行结果:6.声明一个类,此类使用私有的ArrayList来存储对象。
Java语言程序设计(郑莉)第七章课后习题答案
Java语言程序设计第七章课后习题答案1.数组的声明与数组元素的创建有什么关系?答:声明数组仅仅是代表试图创建数组,不分配任何存储空间,声明是为创建做“铺垫”。
2.Vector类的对象与数组有什么关系?什么时候适合使用数组,什么时候适合使用Vector?答:vector是一个能够存放任意对象类型的动态数组,容量能自动扩充,而数组存储固定且类型相同的对象;对于存储固定类型相同的对象使用数组,对于存储不同类型或者动态调整数组大小的情况使用Vector。
3.与顺序查找相比,二分查找有什么优势?使用二分查找的条件?答:对于大数据量中进行查找时二分查找比顺序查找效率高得多;条件是已排序的数组。
4.试举出三种常见的排序算法,并简单说明其排序思路。
答:①选择排序:基本思想是站在未排序列中选一个最小元素,作为已排序子序列,然后再重复地从未排序子序列中选取一个最小元素,把它加到已经排序的序列中,作为已排序子序列的最后一个元素,直到把未排序列中的元素处理完为止。
②插入排序:是将待排序的数据按一定的规则逐一插入到已排序序列中的合适位置处,直到将全部数据都插入为止。
③二分查找:将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
5.声明一个类People,成员变量有姓名、出生日期、性别、身高、体重等;生成10个People 类对象,并放在一个以为数组中,编写方法按身高进行排序。
//People类public class People{private String name;private String birthdaydate;private String sex;private double height;private double weight;public People(){//默认构造函数}public People(People p){=;this.birthdaydate=p.birthdaydate;this.sex=p.sex;this.height=p.height;this.weight=p.weight;}public People(String name,String birthdaydate,String sex,double height,double weight){=name;this.birthdaydate=birthdaydate;this.sex=sex;this.height=height;this.weight=weight;}public String getName() {return name;}public void setName(String name) { = name;}public String getBirthdaydate() {return birthdaydate;}public void setBirthdaydate(String birthdaydate) {this.birthdaydate = birthdaydate;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public String toString(){return"姓名:"+name+"\n出生年月:"+birthdaydate+"\n性别:"+sex+"\n 身高:"+height+"\n体重:"+weight;}}//test7_5类public class test7_5 {/***@param args*/public static void main(String[] args) {// TODO Auto-generated method stubPeople[] people={new People("林楚金","1989年8月13日","男",182,63.5),new People("诸葛亮","181年7月23日","男",184,76.6),new People("迈克杰克逊","1958年8月29日","男",180,60),new People("乔丹","1963年2月17日","男",198,98.1),new People("拿破仑","1769年8月15日","男",159.5,63),new People("苍井空","1983年11月11日","女",155,45),};People temp=new People();for(int i=0;i<people.length-1;i++)for(int j=i+1;j<people.length;j++){if(people[i].getHeight()<people[j].getHeight()){temp=people[j];people[j]=people[i];people[i]=temp;}}System.out.println("按身高从小到大排序后的结果如下:");for(int i=0;i<people.length;i++)System.out.println(people[i]+"\n");}}运行结果:6.声明一个类,此类使用私有的ArrayList来存储对象。
java语言程序设计教程第二版习题解答
习题一1.简述面向对象软件开发方法的重要意义。
【答】:面向对象的软件开发方法按问题论域来设计模块,以对象代表问题解的中心环节,力求符合人们日常的思维习惯,采用―对象+消息‖的程序设计模式,降低或分解问题的难度和复杂性,从而以较小的代价和较高的收益获得较满意的效果,满足软件工程发展需要。
2.解释下面几个概念:1)对象2)实例3)类 4)消息 5)封装 6)继承 7)多态【答】:1)对象:就是现实世界中某个具体的物理实体在计算机中的映射和体现,是由属性和操作所构成的一个封闭整体。
2)实例:是对象在计算机内存中的映像。
3)类:是描述对象的―基本原型‖,是描述性的类别或模板,即对一组对象的抽象。
它定义一组对象所能拥有的共同特征,用以说明该组对象的能力与性质。
4)消息:消息是对象之间进行通信的一种数据结构。
5)封装:封装性是保证软件部件具有优良的模块性的基础。
面向对象的类是封装良好的模块,类定义将其说明(用户可见的外部接口)与实现(用户不可见的内部实现)显式地分开,其内部实现按其具体定义的作用域提供保护。
6)继承:继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。
7)多态:多态性是指一个名字具有多种语义,即指同一消息为不同对象所接受时,可以导致不同的操作。
3.对象―汽车‖与对象―小汽车‖是什么关系,对象―汽车‖与―轮胎‖又是什么关系?【答】:对象―汽车‖与对象―小汽车‖具有继承关系,即对象―小汽车‖继承了对象―汽车‖。
―轮胎‖是对象―汽车‖的一个属性,所以对象―汽车‖包含―轮胎‖,二者是包含关系。
java语言程序设计教程第二版习题解答
习题一简述面向对象软件开发方法的重要意义。
【答】:面向对象的软件开发方法按问题论域来设计模块,以对象代表问题解的中心环节,力求符合人们日常的思维习惯,采用“对象+消息”的程序设计模式,降低或分解问题的难度和复杂性,从而以较小的代价和较高的收益获得较满意的效果,满足软件工程发展需要。
2.解释下面几个概念:1)对象2)实例3)类4)消息5)封装6)继承7)多态【答】:1)对象:就是现实世界中某个具体的物理实体在计算机中的映射和体现,是由属性和操作所构成的一个封闭整体。
2)实例:是对象在计算机内存中的映像。
3)类:是描述对象的“基本原型”,是描述性的类别或模板,即对一组对象的抽象。
它定义一组对象所能拥有的共同特征,用以说明该组对象的能力与性质。
4)消息:消息是对象之间进行通信的一种数据结构。
5)封装:封装性是保证软件部件具有优良的模块性的基础。
面向对象的类是封装良好的模块,类定义将其说明(用户可见的外部接口)与实现(用户不可见的内部实现)显式地分开,其内部实现按其具体定义的作用域提供保护。
6)继承:继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。
7)多态:多态性是指一个名字具有多种语义,即指同一消息为不同对象所接受时,可以导致不同的操作。
对象“汽车”与对象“小汽车”是什么关系,对象“汽车”与“轮胎”又是什么关系?【答】:对象“汽车”与对象“小汽车”具有继承关系,即对象“小汽车”继承了对象“汽车”。
“轮胎”是对象“汽车”的一个属性,所以对象“汽车”包含“轮胎”,二者是包含关系。
简述Java语言的主要特点。
【答】:Java语言的主要特点:(1)简单性(2)面向对象(3)分布式(4)健壮性(5)结构中立(6)安全性(7)可移植(8)解释的(9)高性能(10)多线程(11)动态性5.简述Java语言与C/C++语言的主要差异。
【答】:Java基于C++,与之有许多相似之处,但其设计更易于使用,它们之间主要差异有:(1)Java中无C/C++中最复杂并有潜在危险的指针(2)Java无C/C++中的#include 、#define和头文件。
java程序设计第二版课后答案
java程序设计第二版课后答案Java程序设计第二版课后答案涵盖了多个章节,每个章节都包含了不同的编程概念和练习题。
以下是一些常见章节的课后答案概要,以供参考:第1章:Java简介- 1.1 Java的起源和特点- 1.2 Java平台的组成- 1.3 Java开发环境的搭建第2章:基本语法- 2.1 数据类型- 2.2 变量声明- 2.3 运算符- 2.4 控制语句(if, switch, loop)第3章:控制流程- 3.1 条件语句(if-else, switch-case)- 3.2 循环语句(for, while, do-while)- 3.3 跳转语句(break, continue, return)第4章:数据结构- 4.1 数组的定义和使用- 4.2 字符串的处理- 4.3 集合框架简介第5章:面向对象编程- 5.1 类和对象- 5.2 构造方法- 5.3 继承- 5.4 封装和多态第6章:异常处理- 6.1 异常的概念- 6.2 异常的分类- 6.3 异常的处理方式(try-catch-finally)第7章:输入输出- 7.1 标准输入输出- 7.2 文件输入输出- 7.3 序列化第8章:Java集合框架- 8.1 集合的基本概念- 8.2 List接口及其实现- 8.3 Set接口及其实现- 8.4 Map接口及其实现第9章:泛型- 9.1 泛型的概念- 9.2 泛型的使用- 9.3 泛型的限制第10章:多线程- 10.1 线程的概念- 10.2 创建和启动线程- 10.3 线程的同步第11章:网络编程- 11.1 网络编程基础- 11.2 Socket编程- 11.3 URL和URLConnection第12章:图形用户界面- 12.1 AWT和Swing- 12.2 事件处理- 12.3 布局管理器第13章:Java数据库连接- 13.1 JDBC基础- 13.2 数据库连接和操作- 13.3 SQL语句的使用第14章:Java Web应用- 14.1 Servlet基础- 14.2 JSP技术- 14.3 MVC架构模式每个章节的课后答案通常包括理论问题和编程练习题的解答。
java语言程序设计第二版习题答案
java语言程序设计第二版习题答案Java语言程序设计第二版习题答案Java语言程序设计是一门广泛应用于软件开发领域的编程语言。
无论是初学者还是有经验的开发人员,都可以通过学习Java语言来提升自己的编程能力。
为了帮助读者更好地掌握Java语言的知识,本文将提供《Java语言程序设计第二版》中一些习题的答案,并对其中一些重要的概念进行解释和讨论。
第一章:计算机、程序和Java1.1 问题:编写一个Java程序,输出“Hello, World!”。
答案:```javapublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}}```1.2 问题:Java应用程序的执行过程是怎样的?答案:Java应用程序的执行过程可以分为三个阶段:编辑、编译和运行。
首先,我们使用文本编辑器编写Java源代码文件,文件的扩展名为.java。
然后,使用Java编译器将源代码文件编译成字节码文件,文件的扩展名为.class。
最后,使用Java虚拟机(JVM)加载字节码文件并执行程序。
第二章:基本程序设计2.1 问题:编写一个Java程序,计算两个整数的和。
答案:```javaimport java.util.Scanner;public class Sum {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the first number: ");int num1 = input.nextInt();System.out.print("Enter the second number: ");int num2 = input.nextInt();int sum = num1 + num2;System.out.println("The sum is " + sum);}}```2.2 问题:什么是变量?如何在Java中声明和使用变量?答案:变量是用于存储数据的内存位置。
Java程序设计 精编教程(第2版)习题解答
习题解答习题一(第1章)1.James Gosling2.需3个步骤:1) 用文本编辑器编写源文件.2) 使用javac 编译源文件,得到字节码文件。
3) 使用解释器运行程序.3.set classpath=D :\jdk\jre\lib\rt 。
jar ;.;4. B5。
Java 源文件的扩展名是。
java ,Java 字节码的扩展名是.class 。
6.D 。
习题二(第2章)1.2. Teac her.javapublic class Teacher {double add (double a,double b) {return a+b;}double sub (double a,double b) {return a-b;}}Student 。
javapublic class Student {public void speak () {System 。
out 。
println ("老师好");}}MainClass 。
javapublic class MainClass {public static void main(String args[]) {height bottomTeacher zhang=new Teacher();System.out.println(zhang。
add(12,236));System。
out.println(zhang.add(234,120));Student jiang=new Student();jiang。
speak();}}3.如果源文件中有多个类,但没有public类,那么源文件的名字只要和某个类的名字相同,并且扩展名是.java就可以了,如果有一个类是public类,那么源文件的名字必须与这个类的名字完全相同,扩展名是.java。
4.行尾风格。
习题三(第3章)1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。
Java语言程序设计(第2版)第1-6章课后习题答案
第1章Java语言概述选择题1-1在下列概念中,Java语言只保留了(B)A.运算符重载B.方法重载C.指针D.结构和联合1-2下列关于Java语言特性的描述中,错误的是(D)A.支持多线程操作B.Java程序与平台无关C.Java和程序可以直接访问Internet上的对象D.支持单继承和多继承1-3下列关于JavaApplication程序在结构上的特点的中,错误的是(C)A.Java程序是由一个或多个类组成的B.组成Java程序的若干个类可以放在一个文件中,也可以放在多个文件中C.Java程序的文件名要与某个类名相同D.组成Java程序的多个类中,有且仅有一个主类1-4Java程序经过编译后生成的文件的后缀是(C)A..objB..exeC..classD..java1-5下列关于运行字节码文件的命令行参数的描述中,正确的是(A)A.第一个命令行参数(紧跟命令字的参数)被存放在args[0]中B.第一个命令行参数被存放在args[1]中C.命令行的命令字被存放在args[0]中D.数组args[]的大小与命令行参数的个数无关判断题1-1JavaC++的语言之前问世的。
(错)1-2Java语言具有较好的安全性和可移植性及与平台无关等特性。
(对)1-3Java语言中取消了联合的概念,保留了结构概念。
(错)1-4Java语言中数据类型占内在字节数与平台无关。
(对)1-5Java语言中可用下标和指针两种方式表示数组元素。
(错)1-6Java语言的源程序不是编译型的,而是编译解释型的。
(对)1-7操作系统中进程和线程两个概念是没有区别的。
(错)1-8Java语言既是面向对象的又是面向网络的高级语言。
(对)1-9Java程序分为两大类:一类是Application程序,另一类是Applet程序。
前者又称Java应用程序,后者又称为Java小应用程序。
(对)1-10JavaApplication程序是由多个文件组成的,其中可以有也可以没有主文件。
Java语言程序设计(郑莉)第三章课后习题答案
Java语言程序设计(郑莉)第三章课后习题答案1.设N为自然数:n!=1*2*3*….*n称为n的阶乘,并且规定0!=1.试编程计算2!,4!,6!he 10!.并将结果输出到屏幕上。
答:public class Mul{public static void main(String args[]){int i,n;float s;for(n=0;n<=10;n=n+2){if(n==0)System.out.println("0!=1\n");else{s=1;for(i=1;i<=n;i++)s=s*i;System.out.println(n+"!="+s+"\n");}}}}2.编写程序,接收用户从键键盘上输入的三个整数x,y,z..从中选出最大和最小者,并编程实现。
答:public class Math{public static void main(String args[]){int[] IntArg = new int[args.length];for(int i=0;i<args.length;i++){IntArg[i] = Integer.parseInt(args[i]);}int max,min;max=IntArg[0]>IntArg[1]?IntArg[0]:IntArg[1];max=max>IntArg[2]?max:IntArg[2];min=IntArg[0]<IntArg[1]?IntArg[0]:IntArg[1];min=min<IntArg[2]?min:IntArg[2];System.out.println("max="+max);System.out.println("min="+min);}}3.求出100一枚的宿舍,并将这些数在屏幕上5个乙杭地显示出来。
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));- 2 - staff[1]=new Employee("Carl Carcker",75000,new MyDate(1987,12,15)); staff[2]=new Employee("Tony T ester",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=floatValue*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)- 4 -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);- 6 -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 ResearchT eacher extends Teacher{private String resField;public ResearchT eacher(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 T eacher{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){- 8 -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 ResearchT eacher(){}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;- 10 -}//end public ResearchT eacher(){}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;}- 12 -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;- 14 -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) {Vehicle c1=new Vehicle("vehicle1","white");Vehicle 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 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){- 16 -}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.initVal;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(" ");}- 18 -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 MultipleT able {public void printFormula(int i,int j,int res){ System.out.print(i+"*"+j+"="+res+" "); }public static void main(String[] args) {MultipleT able mt=new MultipleT able();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()- 20 - }//end public class MultipleT able习题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 {- 22 -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");for (int i = 0; i <= 2; i++) { //输入三个数s[i] = Double.parseDouble(input.readLine());} //end for} //end trycatch (NumberFormatException e) {System.out.println("format error!!!");} //end catch- 24 - catch (IOException e) {System.out.print(e);} //end catchTrigsquare ts = new Trigsquare(s[0], s[1], s[2]);if (ts.isTriangle() == true) {System.out.println("三角形的面积是" + ts.getArea());} //end ifelse {System.out.println("输入的三边不能组成三角形!!");} //end else} //end main()} //end public class Trigsquare//习题3.14import java.util.*;import java.io.*;import java.util.Date;import java.text.*;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.GregorianCalendar.*;。
Java语言程序设计(郑莉)第四章课后习题答案
Java语言程序设计第四章课后习题答案1.子类将继承父类所有的属性和方法吗?为什么?答:不,子类不能直接访问从父类中继承的私有属性及方法,但可以对公有及保护方法进行访问。
2.方法的覆盖与方法的重载有何不同?答:覆盖是运用在子类中实现与父类相同的功能,但采用不同的算法或公式;在名字相同的方法中,要做比父类更多的事情;在子类中需要取消从父类继承的方法。
3.声明两个带有无参构造方法的两个类A和B,声明A的子类C,并且声明B为C的一个成员,不声明C 的构造方法。
编写测试代码,生成类C的实例对象,并观察结果。
明一个基类A,它只有一种非默认构造方法;声明A的子类B,B 具有默认方法及非默认方法,并在B的构造方法中调用基类A的构造方法。
明一个类,它具有一种方法,此方法被重载三次,派生一个新类,并增加一种新的重载方法,编写测试类验证四种方法对于派生类验证四种方法对于派生类都有效。
明一个具有final方法的类,声明一个派生类,并试图对这个方法进行重写,会有什么结果。
明一个final类,并试图声明其派生类,会有什么结果。
么是抽象类?抽象类中是否一定要包括抽象方法?答:抽象类是一个不完全的类,不能使用new方法进行实例化。
抽象类可以包含抽象方法,也可以不包含抽象方法,但有抽象方法的必须是抽象类。
和super分别有哪些特殊含义?都有哪些种用法?答:this 表示当前类;super 表示调用父类。
在定义类的时候用到,this是当前对象的引用,super是当前对象的父类对象的引用,一般的都是把super用在构造函数中。
10.完成下面父类及子类的声明:(1) 声明Student类属性包括学号、姓名、英语成绩、数学成绩、计算机成绩和总成绩。
方法包括构造方法、get方法、set方法、toString方法、equals方法、compare方法(比较两个学生的总成绩,结果分为大于、小于、等于),sum方法(计算总成绩)和testScore方法(计算评测成绩)。
java程序设计第二版)课后习题答案
java程序设计(第二版)课后习题答案//习题2.2 import 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 MyDate class 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(\名字:\工资:\雇佣年份:\ }//end print()public void raiseSalary(double byPercent){ salary*=1+byPercent/100; }//endpublic int hireYear(){ return hireDay.getYear(); }}//end class Employee public class MyTestClass {public static void main(String[] args) { Employee[]staff=new Employee[3];staff[0]=new Employee(\staff[1]=new Employee(\ staff[2]=new Employee(\ester\ int integerValue;System.out.println(\ for(integerValue=0;integerValue for(integerValue=0;integerValue}//end class MyTestClass //习题2.4 import 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=floatValue*floatValue;System.out.println(\System.out.println(\布尔类型变量flag=\ System.out.println(\字符型变量yesChar=\ System.out.println(\字节型变量finByte=\ System.out.println(\整型变量intValue=\ System.out.println(\长整型变量longValue=\ System.out.println(\短整型变量shortValue=\ System.out.println(\浮点型变量floatValue=\System.out.println(\双精度浮点型变量doubleValue=\}//end main() }//习题2.9 import java.util.*; class PubTest1{ private int ivar1; privatefloat fvar1,fvar2; public PubTest1(){ fvar2=0.0f; }public float sum_f_I(){ fvar2=fvar1+ivar1; return fvar2; }public void print(){System.out.println(\ }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.10 import 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(\ System.out.println(this.getName()); System.out.print(\ if(this.getSex()==false){ System.out.println(\女\ } else{System.out.println(\男\ }System.out.print(\System.out.println(this.getBirth().getYear()+\this.getBirth().getMonth()+\ this.getBirth().getDay()); System.out.print(\ System.out.println(this.getSalaryID()); System.out.print(\ System.out.println(this.getPosit()); System.out.print(\ 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);。
Java语言程序设计第2版(郑莉)课后习题答案
Java语言程序设计第2版(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加stati c修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加sta t ic修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有publ ic(公共类)及无修饰符(默认类)两种。
区别:当使用publ ic修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protect e及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为pr ivate的成员只能被这个类本身访问,在类外不可见。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java语言程序设计第2版(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
proteced(保护的)用该关键字修饰的成分是受保护的,只可以被同一类及其子类的实例对象访问。
无修饰符(默认的):public,private,protected这个三个限定符不是必须写的。
如果不写,则表明是“friendly”,相应的成分可以被所在保重的各类访问。
8简述构造方法的特点?答:构造方法主要有以下特点:(1)构造方法的方法名与类名相同;(2)构造方法没有返回类型(修饰符void也不能有);(3)构造方法通常被声明为公有的(public);(4)构造方法可以有任意多个参数;(5)构造方法的主要作用是完成对象的初始化工作;(6)构造方法不能在程序中显式的调用;(7)在生成一个对象时,系统会自动调用该类的构造方法为新生成的对象初始化。
9如果在类声明中声明了构造方法,系统是否还提供默认的构造方法?答:用户在进行类声明时,如果没有声明任何构造方法,系统会赋给此类一个默认(无参)的构造方法。
但是,只要用户声明了构造方法,即使没有声明无参的构造方法,系统也不会再赋默认的构造方法。
10:声明Patient类表示在门诊室中的病人。
此类对象应包括name(astring)\sex(achar)、age(an integer)、weight(a float0、allergies(a boolean).声明存取及修改方法。
在一个单独的累中,声明测试方法,并生成两个patient的例子:Atient april=new Patient();April.setname(“zhangli”)April.setSex(‘f’);;April.setage(330;April.setweigeht(154.72);April.setalolergies(true);System.out.println(“那么:”+april.getname());System.out.println(“sex: ”+april.getsex());System.out.println(“age: ”+april.getage());System.outprintln(“weught: ”+april.getweight());\System.out.println(“allergies: ”+april.getallergies());声明并测试toString()方法显示一个病人的aga、sex、name及allergies属性。
答:public class Patient{private String name;private char sex;private int age;private float weight;private boolean allergies;public void setname(String a) {name=a;}public void setsex(char b){sex=b;}public void setage(int c){age=c;}public void setweight(float d) {weight=d;}public void setallergies(boolean e) {allergies=e;}public String getname(){return name;}public char getsex(){return sex;}public int getage(){return age;}public float getweight(){return weight;}public boolean getallergies(){return allergies;}}public class Text{public static void main(String args[]){Patient april=new Patient();april.setname("ZhangLi");april.setsex('f');april.setage(33);april.setweight(154.72f);april.setallergies(true);System.out.println("Name: "+april.getname()); System.out.println("sex: "+april.getsex()); System.out.println("age: "+april.getage()); System.out.println("weight: "+april.getweight()); System.out.println("allergies: "+april.getallergies()); }}11:声明并测试一个复数类,其方法包括toString()及复数的加、减、乘运算。
答:public class Complex{private float a;private float b;public String toString(){if(a!=0)return(a+"i"+"+"+b);else return(""+b);}public Complex(float a,float b){this.a=a;this.b=b;}public void Add(Complex p){this.a+=p.a;this.b+=p.b;}public void Decrease(Complex p){this.a-=p.a;this.b-=p.b;}public void Multiply(Complex p){this.a=this.a*p.a;this.b=this.b*p.b;}}public class ComplexTexter{public static void main(String args[]){Complex a=new Complex(2,4);Complex b=new Complex(5,8);a.Add(b);System.out.println(a.toString()+"\n");a.Decrease(b);System.out.println(a.toString()+"\n");a.Multiply(b);System.out.println(a.toString()+"\n"); }}12:什么是UML?它由哪几部分组成?答:UML是图形化()即可视化的建模语言,成为面向对象建模的标准语言。
它由四部分组成:(1)视图(2)图(3)模型元素(4)通用机制13. 常用的类与类之间的关系有哪几种。
答:有关联、依赖、流、泛化、实现、使用。
14. 考虑学院、系及教员应该具有哪些属性,并画出它们之间关系的类图。
第三章课后习题答案1.设N为自然数:n!=1*2*3*….*n称为n的阶乘,并且规定0!=1.试编程计算2!,4!,6!he 10!.并将结果输出到屏幕上。
答:public class Mul{public static void main(String args[])int i,n;float s;for(n=0;n<=10;n=n+2){if(n==0)System.out.println("0!=1\n"); else{s=1;for(i=1;i<=n;i++)s=s*i;System.out.println(n+"!="+s+"\n"); }}}}2.编写程序,接收用户从键键盘上输入的三个整数x,y,z..从中选出最大和最小者,并编程实现。
答:public class Math{public static void main(String args[]){int[] IntArg = new int[args.length];for(int i=0;i<args.length;i++){IntArg[i] = Integer.parseInt(args[i]);}int max,min;max=IntArg[0]>IntArg[1]?IntArg[0]:IntArg[1];max=max>IntArg[2]?max:IntArg[2];min=IntArg[0]<IntArg[1]?IntArg[0]:IntArg[1];min=min<IntArg[2]?min:IntArg[2];System.out.println("max="+max);System.out.println("min="+min);}}3.求出100一枚的宿舍,并将这些数在屏幕上5个乙杭地显示出来。