JAVA语言程序设计(第2版)第1 6章 课后习题答案
Java语言程序设 第2版 (郑莉)课后习题答案
Java语言程序设计第2版(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
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语言程序设计 第2版 (郑莉)课后习题答案
Java语言程序设计第2版(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
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 下列关于Java Application 程序在结构上的特点的中,错误的是(C)A. Java 程序是由一个或多个类组成的B. 组成Java程序的若干个类可以放在一个文件中,也可以放在多个文件中C. Java 程序的文件名要与某个类名相同D. 组成Java程序的多个类中,有且仅有一个主类1-4 Java 程序经过编译后生成的文件的后缀是(C)A. .objB. .exeC. .classD. .java1-5 下列关于运行字节码文件的命令行参数的描述中,正确的是( A )A. 第一个命令行参数(紧跟命令字的参数)被存放在args[0]中B. 第一个命令行参数被存放在args[1]中C. 命令行的命令字被存放在args[0]中D.数组args[]的大小与命令行参数的个数无关判断题1-1 JavaC++的语言之前问世的。
(错)1-2 Java语言具有较好的安全性和可移植性及与平台无关等特性。
(对)1-3 Java语言中取消了联合的概念,保留了结构概念。
(错)1-4 Java语言中数据类型占内在字节数与平台无关。
(对)1-5 Java语言中可用下标和指针两种方式表示数组元素。
(错)1-6 Java语言的源程序不是编译型的,而是编译解释型的。
(对)1-7 操作系统中进程和线程两个概念是没有区别的。
(错)1-8 Java语言既是面向对象的又是面向网络的高级语言。
(对)1-9 Java 程序分为两大类:一类是Application 程序,另一类是Applet 程序。
前者又称Java应用程序,后者又称为Java小应用程序。
java语言程序设计教程第二版习题解答
习题一1.简述面向对象软件开发方法的重要意义。
【答】:面向对象的软件开发方法按问题论域来设计模块,以对象代表问题解的中心环节,力求符合人们日常的思维习惯,采用―对象+消息‖的程序设计模式,降低或分解问题的难度和复杂性,从而以较小的代价和较高的收益获得较满意的效果,满足软件工程发展需要。
2.解释下面几个概念:1)对象2)实例3)类 4)消息 5)封装 6)继承 7)多态【答】:1)对象:就是现实世界中某个具体的物理实体在计算机中的映射和体现,是由属性和操作所构成的一个封闭整体。
2)实例:是对象在计算机内存中的映像。
3)类:是描述对象的―基本原型‖,是描述性的类别或模板,即对一组对象的抽象。
它定义一组对象所能拥有的共同特征,用以说明该组对象的能力与性质。
4)消息:消息是对象之间进行通信的一种数据结构。
5)封装:封装性是保证软件部件具有优良的模块性的基础。
面向对象的类是封装良好的模块,类定义将其说明(用户可见的外部接口)与实现(用户不可见的内部实现)显式地分开,其内部实现按其具体定义的作用域提供保护。
6)继承:继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。
7)多态:多态性是指一个名字具有多种语义,即指同一消息为不同对象所接受时,可以导致不同的操作。
3.对象―汽车‖与对象―小汽车‖是什么关系,对象―汽车‖与―轮胎‖又是什么关系?【答】:对象―汽车‖与对象―小汽车‖具有继承关系,即对象―小汽车‖继承了对象―汽车‖。
―轮胎‖是对象―汽车‖的一个属性,所以对象―汽车‖包含―轮胎‖,二者是包含关系。
(雍俊海)JAVA程序设计教程_第2版 课后答案
第一章:P561、列出在你过去学习工作中用过与计算机图形学有关的程序c语言:#include<graphics.h>main(){intgraphdriver=VGA,graphmode=VGAHI;initgraph(&graphdriver,&graphmode,””);setbkcolor(BLUE);setcolor(WHITE);setfillstyle(1,LIGHTRED);bar3d(100,200,400,350,100,1);floodfill(450,300,WHITE);floodfill(250,450,WHITE);setcolor(LIGHTGREEN);rectangle(450,400,500,450);floodfill(470,420,LIGHTGREEN);getch();closegraph();}JAVA语言:例1、画点Importjava.io.*;Classpoint{intax;intay;intbx;intby;publicpoint(intax,intay,intbx,intby){floatk;//计算斜率floatb;k=(by-ay)/(bx-ax);b=ay-ax*k;system.out.println(“直线的方程为:y=”+k+”x”+”+”+b);}}例2、画矩形classDrawPanelextendsJpanel{publicvoidpaint(Graphicsg){super.paint(g);Graphics2Dg2=(Graphics2D);Doubleleftx=200;Doubletopy=200;Doublewidth=300;Doubleheight=250;Rectangle2Drect=newRectangle2D.double(leftx,topy,width,height);G2.draw(rect);}}2、列出你所用过的窗口系统中与观感有关的元素的功能,如图标、滚动棒、菜单等使用滚动条当文档、网页或图片超出窗口大小时,会出现滚动条,可用于查看当前处于视图之外的信息。
JAVA程序设计使用教程(第2版)答案
}//end speak() }//end class
第二章习题答案
一、 简答题 1.Java 提供了哪些注释语句,功能有什么不同? Java 语言提供了 3 种形式的注释: (1)// 一行的注释内容 以//开始,最后以回车结束,表示从//到本行结束的所有字符均作为注释内容 (2)/*一行或多行的注释内容*/ 从/*到*/ 间的所有字符(可能包括几行内容)都作为注释内容。 以上两种注释可用于程序的任何位置。 (3)/**文档注释内容*/ 当这类注释出现在任何声明之前时将会作特殊处理,它们不能再用在代码的任何地 方。这类注释意味着被括起来的正文部分,应该作为声明项目的描述,而被包含在自动产生 的文档中。 2.识别下面标识符,哪些是合法的,哪些是非法的。 Ply_1,$32,java,myMothod,While,your-list,class,ourFriendGroup_$110,长度, 7st 合法标识符:Ply_1,$32,java,myMothod,ourFriendGroup_$110,While 不合法标识符:class(关键字) ,长度,7st 3.Java 提供了哪些数据类型,全部写出来。
//3、编程,根据考试成绩的等级打印出分数段,优秀为 90 以上,良好为 80~90,中等 为 70~79,及格为 60~69,60 以下为不及格,要求采用 switch 语句。 public class XT00203 { public static void main(String args[]) { int a[]={85,95,65,53,77,68,45,99,100}; int i,l; for (i=0;i<=a.length;i++){ l=a[i]/10; switch(l) { case 9: case 10: System.out.println("成绩是:"+a[i]+":等级是"+"优秀"); break; case 8: System.out.println("成绩是:"+a[i]+":等级是"+"良好"); break;
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中声明和使用变量?答案:变量是用于存储数据的内存位置。
JAVAWEB 程序设计 习题参考答案(第1 6章)
从表单中获取多个值用 getParameterValues,求数组的长度为 length。
7、用户使用 POST 方式提交的数据中存在汉字(使用 GBK 字符集) ,在 Servlet 中需要使用 下面____个语句处理。 A、request.setCharcterEncoding(“GBK”); B、request.setContentType(“text/html;charset=GBK”); C、reponse.setCharcterEncoding(“GBK”); D、response.setContentType(“text/html;charset=GBK”); 参考答案:A 其中 D 是设置响应的方式的,A 是设置请求的方法。其他两个是错误的。选择:A 8、简述 Servlet 的生命周期。Servlet 在第一次和第二次被访问时,生命周期方法的执行有何 区别。 参考答案: 1、 在 Servlet 容器刚被启动时加载,也可以在容器收到客户请求服务时加载 <servlet> <load-on-startup>1</load-on-startup> </servlet> 标签<load-on-startup>配置该 Servlet 的加载方式, 可选值为 0 和 1, 如果配置为 1.Tomcat 会在启动时候加载该 Servlet,否则,Tomcat 会在有人第一次请求该 Servlet 时才加载该 Servlet 2、 加载成功后,Servlet 容器便可以创建一个 Servlet 实例。Servlet 加载并实例化后,在处 理客户端请求前,容器必须通过调用它的 init 方法进行初始化 3、 实例创建好后,就要对其初始化。Servlet 的 init()方法的主要任务就是完成初始化工作。 该方法由 Servlet 容器调用完成。对于每一个 Servlet 实例,该方法只允许被调用一次。 4、 利用 service 处理请求 在 Servlet 被成功初始化后容器就可以使用它去处理客户端发来的请求了。在使用 HTTP 协议发送请求时,容器必须提供代表请求和回应的 HttpServletRequest 对象和 HttpServlerRespons 5、利用 destroy()方法终止服务 在 Servlet 执行完毕或是在处理请求过程中出现 UnavailiableException 异常,需要移除 Servlet,在移除之前,Servlet 会调用 destroy()方法让 Servlet 自动释放占用的资源。 第一次访问时会执行 init()方法,第二次访问不会执行 init()方法。 9、简述转发和重定向跳转方式的区别,在 Servlet 中分别使用什么方法实现? 重定向跳转方式的区别:转发和重定向都可以使浏览器获得另外一个 URL 所指向的资 源,区别是转发共享同一个请求对象,而重定向不共享同一个请求对象。 在 Servlet 中分别使用什么方法实现?在 Servlet 中转发使用 RequestDespacher 接口的 forward()方法实现。重定向由 HttpServletResponse 接口的 sendRedirect()方法实现。
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程序设计教程第二版课后答案
java程序设计教程第二版课后答案【篇一:《java程序设计》课后习题参考答案】参考答案――武汉大学出版社习题1参考答案1.java语言的特点有哪些??答:参考1.1.2防止直接访问数据变量看起来有些奇怪,但它实际上却对使用类的程序质量有极大的好处。
既然数据的单个项是不可访问的,那么惟一的办法就是通过方法来读或写。
因此,如果要求类成员内部的一致性,就应该通过类本身的方法来处理。
这种数据隐藏技术就是面向对象的重要特性——封装。
它将类的外部界面与类功能的实现区分开来,隐藏实现细节,(通过公共方法)保留有限的对外接口,迫使用户使用外部界面,通过访问接口实现对数据的操作。
即使实现细节发生了改变,还可通过界面承担其功能而保留原样,确保调用它的代码还继续工作,这使代码维护更简单。
2.简述封装的优点。
?答:封装是一个简单而有效的思想,优点有:(1)模块化,对内成为一个结构完整、可进行自我管理、自我平衡、高度集中的整体。
(2)信息隐蔽,对外则是一个功能明确、接口单一、可在各种适合的环境下都能独立工作的有机单元。
面向对象的程序设计实现了对象的封装,使得用户不必关心诸如对象的行为是如何实现的这样一些细节。
通过对对象的封装,实现了模块化和信息隐藏,有利于程序的可移植性和安全性,同时也有利于对复杂对象的管理。
类的封装性使得代码的可重用性大为提高,这样的有机单元特别适合构建大型标准化的软件系统,具有很高的开发效率。
3.java的基本工具有哪些??(1) javac 编译器(2) java 解释器(3) jdb java 语言调试器(4) javadoc api文档管理器(5) javah 头文件生成器(6) appletviewer 小应用程序浏览器(7) javap 类文件反汇编器4.java开发环境是如何配置的?答:对于windows 2000以上版本的操作系统,可以打开[控制面板]窗口,双击其中的[系统]图标,在[系统特性]窗口中单击[高级]选项卡,进而单击[环境变量]按钮。
JAVA程序设计之网络编程(第2版)各章习题和思考题答案
Java程序设计各章习题和思考题答案第一章习题和思考题答案1、Java程序是由什么组成的?一个程序中必须有public类吗?Java 源文件的命名规则是怎样的?答:一个Java源程序是由若干个类组成。
一个Java程序不一定需要有public类:如果源文件中有多个类时,则只能有一个类是public类;如果源文件中只有一个类,则不将该类写成public也将默认它为主类。
源文件命名时要求源文件主名应与主类(即用public修饰的类)的类名相同,扩展名为.java。
如果没有定义public类,则可以任何一个类名为主文件名,当然这是不主张的,因为它将无法进行被继承使用。
另外,对Applet小应用程序来说,其主类必须为public,否则虽然在一些编译编译平台下可以通过(在BlueJ下无法通过)但运行时无法显示结果。
2、怎样区分应用程序和小应用程序?应用程序的主类和小应用程序的主类必须用public修饰吗?答:Java Application是完整的程序,需要独立的解释器来解释运行;而Java Applet则是嵌在HTML编写的Web页面中的非独立运行程序,由Web 浏览器内部包含的Java解释器来解释运行。
在源程序代码中两者的主要区别是:任何一个Java Application应用程序必须有且只有一个main方法,它是整个程序的入口方法;任何一个Applet小应用程序要求程序中有且必须有一个类是系统类Applet的子类,即该类头部分以extends Applet结尾。
应用程序的主类当源文件中只有一个类时不必用public修饰,但当有多于一个类时则主类必须用public修饰。
小应用程序的主类在任何时候都需要用public来修饰。
3、开发与运行Java应用程序需要经过哪些主要步骤和过程?答:主要有三个步骤(1)、用文字编辑器notepad(或在Jcreator,Gel,BuleJ,Eclipse,Jbuilder等)编写源文件;(2)、使用Java编译器(如Javac.exe)将.java源文件编译成字节码文件.class;(3)、运行Java程序:对应用程序应通过Java解释器(如java.exe)来运行。
Java程序设计精编教程第2版习题解答
习题解答习题一(第1章)1.2.需3个步骤:1) 用文本编辑器编写源文件。
2) 使用编译源文件,得到字节码文件。
3) 使用解释器运行程序。
3. :\\\\;.;4. B5. 源文件的扩展名是,字节码的扩展名是。
6.D 。
习题二(第2章)1.2. { ( b) {;}( b) {;}}{() {("老师好");}}{( []) {();((12,236));((234,120));();();}}3.如果源文件中有多个类,但没有类,那么源文件的名字只要和某个类的名字相同,并且扩展名是就可以了,如果有一个类是类,那么源文件的名字必须与这个类的名字完全相同,扩展名是。
4.行尾风格。
习题三(第3章)1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。
标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。
不是标识符。
2.关键字就是语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。
不是关键字。
3.,,,,,,,。
4.属于操作题,解答略。
5.属于操作题,解答略。
6. E {( [ ]) {'A''Z';( <)(" ");}}7.不可以。
习题四(第4章)1.110。
不规范。
2.新亲亲斤!!。
3.{( ) {(913112) {("是三等奖");}(20959627) {("是二等奖");}(87531659) {("是一等奖");{("未中奖");}}}4.;{( []) {();= 0; 存放电量= 0; 用户需要交纳的电费("输入电量:");();( <= 90 >=1){= *0.6计算的值}( <= 150 >=91){= 90*0.6+(90)*1.1计算的值}(>150){= 90*0.6+(150-90)*1.1+(150)*1.7计算的值}{("输入电量:""不合理");}("电费5.2f");}}5. E {( [ ]) {'A''Z';( <)("%2c");();( <)("%2c",(32));}}6. 5 {( []) {0;(1<=1000) {(0);}()("完数:");}}}7E {( []) {111;0;() {1;(1<){*i;};(>9876);;}("满足条件的最大整数:"+(1));}}习题五(第5章)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版)习题参考答案(1-9章)
各章参考答案(1-9章)第一章【习题内容】1. Java语言有哪些特点?2.简述Java的运行机制。
3.简述Java应用程序的开发过程。
4.在计算机上安装、配置Java运行环境,并编辑运行本章中的例程。
【参考答案】1.面向对象、语法简单、平台无关性、安全性、分布式应用、多线程2. Java程序的运行必须经过编写、编译、运行三个步骤。
编写是指在Java开发环境中进行程序代码的输入,最终形成后缀名为.java的Java源文件。
编译是指使用Java编译器对源文件进行错误排查的过程,编译后将生成后缀名为.class的字节码文件,字节码文件是一种和任何具体机器环境及操作系统环境无关的中间代码,它是一种二进制文件,Java解释器负责将字节码文件翻译成具体硬件环境和操作系统平台下的机器代码,以便执行。
运行是指使用Java解释器将字节码文件翻译成机器代码,执行并显示结果。
Java虚拟机(JVM)是运行Java程序的软件环境,Java解释器就是Java虚拟机的一部分。
在运行Java 程序时,首先会启动JVM,然后由它来负责解释执行Java的字节码,JVM把不同软硬件平台的具体差别隐藏起来,从而实现了真正的二进制代码级的跨平台移植。
3.(1)安装JDK(2)配置环境变量(3)使用记事本编写java源文件(4)使用javac 编译java源文件(5)使用java运行java程序。
4.略。
第二章【习题内容】1. 现有语句:String s = "Example"; 则下面哪些语句是合法语句?A. s >>> = 3;B. s[3] = "x";C. int i = s.length();D. String t = "For " + s;E. s = s + 10;2.下面哪些是Java保留字?A. runB. defaultC. implementD. import3.下面声明float变量的语句合法的有:A. float foo = -1;B. float foo = 1.0;C. float foo = 42e1;D. float foo = 2.02f;E. float foo = 3.03d;F. float foo = 0x0123;4.以下哪两个表达式是等价的:A. 3/2B. 3<2C. 3*4D. 3<<2E. 3*2^2F. 3<<<25.分析下列程序的执行结果:(1)public class TestA{public static void main(String args[]){int i = oxFFFFFFF1;int j = ~i;System.out.println("j=" + j);}}(2)public class TestB{public static void main(String[] args){System.out.println(6 ^ 3);}}(3)public class FooBar{public static void main(String[] args){int i = 0, j = 5;tp:for(; ; i++){for( ; ; --j)if(i > j)break tp;}System.out.println("i=" + i + ",j=" + j);}}(4)public class TestC{public static void main(String[] args){int i = 1, j = 10;do{if(i++ > --j)continue;}while(i < 5);System.out.println("i=" + i + " j=" + j);}}【参考答案】1. C、D、E2.B、D3.A、D、F4.C、D5.(1)j=14(2)5(3)i=0,j=-1(4)i=5 j=6第三章【习题内容】1.什么叫引用类型,对象是引用类型吗?2.Java的访问限定修饰符有几种,各自的访问权限是什么?3.什么是类成员,什么是实例成员?它们之间有什么区别?4.如何创建自己的包,如何引入包?5.下面哪一个是类Myclass的构造方法?class Myclass{public void Myclass(){}public static Myclass(){}public Myclass(){}public static void Myclass(){}}6.设计一个动物类,它包含动物的基本属性,例如名称、身长、重量等,并设计相应的动作,例如跑、跳、走等。
JavaWeb_程序的设计_习题参考答案(第1-6章)
《JavaWeb程序设计》练习题参考答案第一章:Servlet基础1、下列选项中属于动态技术的是_________(多选)答:PHP/ASP/JSPA、PHPB、ASPC、JavaScriptD、JSP参考答案:PHP(Hypertext Preprocessor):超文本预处理器,其语法大量借鉴C、Java、Perl等语言,只需要很少的编程知识就能使用PHP建立一个真正交互的Web站点,由于PHP开放源代码,并且是免费的,所以非常流行,是当今Internet上最为火热的脚本语言之一。
ASP(Active Server Pages):是一种类似HTML、Script与CGI结合体的技术,他没有提供自己专门的编程语言,允许用户使用许多已有的脚本语言编写ASP应用程序局限于微软的IIS,般只适用于中小型站点,但目前ASP升级演变而来的支持大型的开发。
JSP(Java ServerPages):是基于Java Servlet以及Java体系的Web开发技术。
能在大部分服务器上运行,而且易于维护和管理,安全性能方面也被认为是三种基本动态技术中最好的。
2、下列关于Servlet的说确的是_______(多选)A、Servlet是一种动态技术B、Servlet运行在服务端C、Servlet针对每个请求使用一个进程来处理D、Servlet与普通的Java类一样,可以直接运行,不需要环境支持参考答案:Servlet是一种动态技术,是运行在服务器端,Servlet针对每个请求使用一个线程来处理,而不是启动一个进程,传统的CGI为每次请求启动一个进程来处理。
所以Servlet的效率更高3、下列关于Servlet的编写方式正确的是______(多选)A、必须是HttpServlet的子类B、通常需要覆盖doGet() 和doPost()方法或其一C、通常需要覆盖service()方法D、通常要在web.xml文件中声明<servlet>和<servlet-mapping>两个元素参考答案:A、B、D必须继承Httpservlet类,不需要覆盖servlce()方法,service()方法是Servlet接口中的方法,Servlet是HttpServlet的父类,该方法会根据请求类型选择执行doGet()或doPost()方法。
Java第2版-习题参考答案
习题参考答案——Java程序设计实用教程(第2版)第1章绪论1.1 (1)简单性——Java对系统软、硬件要求低;也比较容易学习。
(2)面向对象——Java是纯面向对象的语言。
(3)分布性——Java是面向网络的语言;支持数据分布和操作分布。
(4)鲁棒性——说明Java的健壮性很好,不会轻易造成系统崩溃。
(5)安全性——在防止非法入侵方面表现突出。
(6)体系结构中立——可以在任意的处理器上运行,也可在不同的平台上运行。
(7)可移植性——采用Java虚拟机机制,体现Java最初的开发理念,可跨平台运行。
(8)解释型——Java解释器直接对Java字节码进行解释执行,在单机上运行时速度较慢。
(9)高性能——由于Java字节码的设计,使得它能很容易地直接转换成对应于特定CPU的机器码,从而得到较高的性能。
用Java编写的程序在网络上运行时,其运行速度快。
(10)多线程——在Java中内置了对多线程的支持,使用多线程机制提高了程序性能,可以充分利用CPU。
(11)动态性——Java自身的设计使得它更适合于不断发展的环境,在Java类库中可以自由地加入新的方法和实例变量,而不会影响用户应用程序的执行。
1.2 Java在语法中取消了C/C++中具有的不安全的特性,如取消了指针,使得非法访问被杜绝。
用户不可能造成内存分配错误,也用不着专门提防可能出现的内存漏洞。
1.3 主要是由于Java程序可以方便地被移植到网络上的不同机器。
另外,Java的类库中也实现了与不同平台的接口,使这些类库可以移植。
1.4 对象是类的特例。
1.5 略。
1.6 略。
第2章绪论2.1 略。
2.2 略。
2.3 进行SET PA TH设置是为了让系统找到Java.exe、Javac.exe在什么文件夹中;SET CLASSPA TH设置的作用是查找类路径变量的。
2.4 Java程序被分为两类,一类是Java Application程序,另一类是Java Applet程序。
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)。
D. a!=b?c:d 2-18 下列关于条件语句的描述中,错误的是 A,C 。 A. If 语句可以有多个 else 子句和 else if 子句 B. If 语句中可以没有 else 子句和 else if 子句 C. If 语句中的〈条件〉可以使用任何表达式 D. If 语句的 if 体、else 体内可以有循环语句 2-19 下列关于开关语句的描述中,错误的是 B,C,D 。 A. 开关语句中,default 子句可以省略 B. 开关语句中,case 子句的〈语句序列〉中一定含有 break 语句 C. 开关语句中,case 子句和 default 子句都可以有多个 D. 退出开关语句的唯一条件是执行 break 语句 2-20 下列关于循环语句的描述中,错误的是 B,D 。 A. 任何一种循环体内都可以包含一种循环语句 B. 循环体可以是空语句,也可以是空 C. 循环体内可以出现多个 break 语句 D. 循环语句中,循环体至少被执行一次 2-21 下列循环语句的循环次数是 D 。 int i=5; do{ System.out.println(i--); i--; }while(i!=0); A. 0 B. 1 C. 5 D. 无限 2-22 下列循环语句中,循环体被执行的次数为 D 。 for (int i=0,j=0;(j!=18)||(i<4);i++) A. 3 B. 4 C. 不确定 D. 无限 2-23 下列关于 Java 语言的数组描述中,错误的是 D 。 A. 数组的长度通常用 length 来表示 B. 数组下标从 0 开始 C. 数组元素是按顺序存放在内在的 D. 数组在赋初值和赋值时都不判界 2-24 下列关于数组的定义形式,错误的是 A,C,D 。 A. int[]a;a=new int; B. char b[];b=new char[80] C. int[]c=new char[10] D. int[]d[3]=new int[2][] 2-25 下列关于字符串的描述中,错误的是 B 。 A. Java 语言中,字符串分为字符串常量和字符串变量两种
第2章
Java 语言语法基础
选择题 2-1 Java 语言所用的字符集中字符是 B 位。 A. 8 B. 16 C. 32 D. 64 2-2 下列关于标识符的描述中,正确的是 A 。 A. 标识符中可以使用下划线和美元符 B. 标识符中可以使用连接符和井号符 C. 标识符中大小写字母是无区别的 D. 标识符可选用关键字 2-3 Java 语言和各种分隔符中,非法的是 D 。 A. 空白符 B. 分号 C. 逗号 D. 问号 2-4 下列是 Java 语言中可用的注释,其中错误的是 C 。 A. // B. /*…*/ C. /**…**/ D. /**…*/ 2-5 Java 语言中字符型数据的长度是 B 位。 A. 8 B. 16 C. 32 D. 64 2-6 下列描述的两种数据类型的长度不相等的是 A 。 A. 字符型和布尔型 B. 字节型和布尔型 C. 短整型和字符型 D. 整型和单精度浮点型 2-7 下列是 Java 语言中的复合数据类型,其中错误的是 C 。 A. 数组 B. 接口 C. 枚举 D. 类 2-8 下面是关于 Java 语言中数据类型的强制转换的描述,其中错误的是 C,D 。 A. 当数据类型从高转换为低时需强制转换 B. 强制转换时使用强制转换去处符,形如(<类型>) C. 浮点型数据强制转换为整型时,小数部分四舍五入 D. 赋值操作中都要采用强制类型转换 2-9 下列关于常量的描述中,错误的是 B,D 。 A. Java 语言的常量有 5 种
B. 浮点型数 12.456 是单精度的 C. 布尔型常量只有两个可选值:true 和 false D. 字符串常量含有结束符'\0 ' 2-10 下列关于定义符号常量的描述中,错误的是 A,C 。 A. 定义符号常量使用关键字 const B. 定义符号常量时要赋初值 C. 符号常量既可以定义为类成员,又可在方法中定义 D. 定义符号常量时必须给出数据类型 2-11 下列关于变量的默认值的描述,其中错误的是 B,C 。 A. 定义变量而没有进行初始化时,该变量具有默认值 B. 字符型变量的默认值为换行符 C. 布尔型变量的默认值是 true D. 变量的默认值是可以被改变的 2-12 下列关于变量定义的描述中,正确的是 A,C 。 A. 定义变量时至少应指出变量名字和类型 B. 定义变量时没有给出初值该变量可能是无意义值 C. 定义变量时,同一个类型多个变量间可用逗号分隔 D. 定义变量时必须要给变量初始化 2-13 下列关于变量作用域的描述,错误的是 D 。 A. 在某个作用域定义的变量,仅在该作用域内是可见的,而在该作用域外是不可 见的 B. 在类中定义的变量的作用域在该类中的方法内可以使用 C. 在方法中定义 的变量的作用域仅在该方法体内 D. 在方法中作用域可嵌套,在嵌套的作用域中可以定义同名变量 2-14 下列关于增 1(++)减 1(--)1 运算符的描述中,正确的是 A,B 。 A. 增 1 减 1 运算符都是单目运算符 B. 增 1 减 1 运算符都具有前缀运算和后缀运算 C. 增 1 减 1 运算符不会改变变量的值 D. 增 1 减 1 运算符前缀运算和后缀运算后表达式值是相同的 2-15 关于运算符优先级的描述中,错误的是 D 。 A. 在表达式中,优先级高的运算符先进行计算 B. 赋值运算符优先级最高 C. 单目运算符优先级高于双目和三目运算符 D. 逻辑运算符优先级高于逻辑位运算符 2-16 下列关于表达式的描述中,正确的是 A,C 。 A. 任何表达式都有确定的值和类型 B. 算数表达式的类型由第一个操作数的类型决定 C. 逻辑表达式的操作数是逻辑型的 D. 赋值表达式的类型取决于右值表达式的类型 2-17 下列表达式中,非法的是 B,C 。 int a=5,b=6;double c=1.1,d=2.2 A. a+c+++d B. (a+c0 Java 程序中出现的输出方法 println()和 print()是完全一致的。 (错) 分析程序的输出结果题 1-1 程序 Exerl_1.java import java.io.*; public class Exerl_1 { public static void main (String args[ ]) { System.out.print("This is a "); System.out.println("strint.") } } 该程序的输出结果如下: This is a string. 1-2 程序 Exerl_2.java Import java.io.*; Public class Exerl_2 { Public static void mian(String args[ ]) { Char ch=" "; System.out.println("Input a character:"); Try{ ch=(char)System.in.read(); } Catch(IOException e) { } System.out.println("The character is \'"+ch+"\'"); } } 该程序的输出结果如下 Input a character:k↙ The character is ‘k’ 1-3 程序 Exerl_3.java import java.io.*; public class Exerl_3 { Public static void main(String args[ ]) { String str= " " System.out.println("Input a string:"); Try{ BufferedReader in =new BufferedReader(new InputStreamReader(System.in)); str=in.readLine();
参考程序内容如下: import java.io.*; public class prol_2 { public static void main(String args[ ]) { int var1=10; double var2=19.5; System.out.println("var1="+var1+",var2="+var2); System.out.println("ok!"); } }
} Catch(IOException e ) { } System.out.println("The string is \'"+str+ "\ " "); } } 1-4 程序 Exerl_4.java import java.io.* public class Exerl_4 { public static void main(String args[ ]) { A a=new A; a.i=8; a.d=1.25; a.meth("该程序输出结果如下所示"); System.out.println("\ti="+a.i+",d="+a.d); } } class A { int i; double d; void meth(string str) { System.out.println(str); } } 该程序输出结果如下所示 i=8,d=1.25 编程题 1-1 编写一个 Java Application 程序,使该程序运行后输出字符串"Hello!How are you."。 参考程序内容如下 import java.io.*; public class prol_1 { public static void main(String args[ ]) { System.out.println("Hello!How are you."); } } 1-2 编写一个 Java Application 程序,使该程序输出显示如下结果: Var1=10,var2=19.5 Ok!