Java程序设计案例教程(第二版)周怡、张英主编。第3章 习题答案
Java程序设计案例教程(第二版)周怡、张英主编。第3章 习题答案

习题 3
一、判断题 1.Java 的 各 种 数 据 类 型 占 用 固 定 长 度 , 与 具 体 的 软 硬 件 平 台 环 境 无 关 。 ( √ ) 难度:容易 参考出处: 3.2 节 2.用“+”可以实现字符串的拼接,用“-”可以从一个字符串中去除一个字符子串。(× ) 难度:容易 参考出处: 3.5 节 3.Java 不区分大小写的语言。(×) 难度:容易 参考出处: 3.1.1 节 4.Java 的 String 类的对象既可以是字符串常量,也可以是字符串变量。(√ ) 难度:容易 参考出处: 3.4 节 5.注释的作用是使程序在执行时在屏幕上显示//之后的内容。(√ ) 难度:容易 参考出处: 3.1.4 节 6.在 Java 的方法中定义一个常量要用 const 关键字。( × ) 难度:容易 参考出处: 3.4.1 节 二、选择题 1.Java 语言中语句是以 C 作为结束的。 A.句号 B.引号 C.分号 D.括号 2. 初次在医院进行挂号的患者需要提供其基本信息,其中年龄数据类型的定义形式为 A 。 A.int B.double C.char D.boolean 3.下面的 Java 的标识符哪个是合法的 A 。 A.$患者编号 B.患者 姓名 C.患者-年龄 D.1 患者婚否 4.关于数据类型转换,下面描述中错误的是 C 。 A.int 类型可以转换成 float 类型数据 B.long 类型可以转换成 short 类型数据 C.long 类型不可以转换成 short 类型数据 D.数据类型不一致时,必须进行数据类型的转换才能进行赋值 5.以下数据类型最高级的是 D 。 A.short B.int C.char D.float 6.设 int x = 1 , y = 2 则表达式 x+=++y 运行后 x 的值是 A 。 A.4 B.3 C.2 D.1 7.换行符的正确转义字符是 C 。 A./n B.\r C.\n D./r 三、填空题 1.整型类型的变量有字节型 、 短整型 、 整型 、 长整型 。 2.Java 中,逻辑常量的值有 true 和 false 。 3.表达式(15>20 ? 1 : 2)的值为 2 。 4.执行语句 int s=(int)123.45 之后,变量 s 的值为 123 。 5.现有 2 个 char 类型的变量 x='a',y=3,当执行 x=(char)(x+y);语句之后,x 的值应该是 100 。 6.Java 中定义常量必须使用的关键字是 final 。 四、简答题 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版)第3章_运算符、表达式和语句

if-else if-else 语句是多条件分支语句,即根据多个条 件来控制程序执行的流程。 if-else if-else语句的语法格式:
if(表达式) { 若干语句 } else if(表达式) { 若干语句 } …… else { 若干语句 }
2017/8/16
18
例3-1
Number.java , Example3_1.java
2017/8/16
5
§3.1.3 算术混合运算的精度
精度从“低”到“高”排列的顺序是: byte short char int l ong float double Java在计算算术表达式的值时,使用下列计算精度规则: 1 .如果表达式中有双精度浮点数( double 型数据),则 按双精度进行运算。 2 .如果表达式中最高精度是单精度浮点数( float 型数 据),则按单精度进行运算。 3.如果表达式中最高精度是long型整数,则按long精度进 行运算。 4.如果表达式中最高精度低于 int型整数,则按int精度进 行运算。
if(表达式) { 若干语句 } else { 若干语句 }
有语法错误的if-else语句 :× 正确的写法是:√
if(x>0) y=10; z=20; else y=-1020; } else y=100;
17
§3.3.3 if-else if-else 语句
2017/8/16 21
§3.5 循环语句 §3.5.1 for循环语句 for语句的语法格式:
for (表达式1; 表达式2; 表达式3) { 若干语句 }
for语句的执行规则是:
( 1 )计算“表达式 1 ”,完成必要的初始化 工作。 (2)判断“表达式2”的值,若“表达式2” 的值为true,则进行(3),否则进行(4)。 ( 3 )执行循环体,然后计算“表达式 3 ”, 以便改变循环条件,进行(2)。 (4)结束for语句的执行。
Java语言程序设计(第二版)课件第3章 流程控制

常量值必须是与表 达式类型兼容,且 不能重复,break 跳出case语句段
若所有的case都 不匹配,则可去 执行default语
句
3.2 循环结构
1、while 循环
while(条件) { 语句组; }
2、do-while循环
注意:两者的区别, 1先判断条件,成立 才执行。2先执行在
判断条件。
5
public class SignFunction{ public static void main(String args[]) { int intx; intx=0; if(intx>0)
System.out.println(intx+" is + ;"); else{ if(intx<0)
System.out.println(intx+" is - ;"); else System.out.println(intx+" is 0 ;"); } } }
开始处,结束本次循环,继续执行下一次循 环, continue 语句之后的语句将不再执行。
8
综合实例
public class BreakDemo{
public static args[]){
void
main(String
for(int i=1;i<100;i+=2){
if(i>10)break;
System.out.println("i = "+i);
第3章
控制结构
回顾
• 掌握标识符的定义规则 • 掌握各种简单数据类型的使用 • 掌握运算符和表达式的使用 • 掌握Java程序简单的输入输出方法 • 了解常用的保留字和分隔符
Java程序设计案例教程(第二版)周怡、张英主编。第7章习题参考答案

第7章包与异常处理习题参考答案:一、判断题1.在编程中,可以不用进行异常的处理,因为有时发生的异常并不会影响程序的正常运行_____×__。
2.异常处理一般可用try ……catch语句进行处理的____√___。
3.try ……catch语句不能进行嵌套使用_×______。
4.如果觉得系统给出的异常类不够使用,也可能定义自己的异常类,自己定义的异常类一般继承Exception类(或其子类)___√____。
5.try……catch……finally语句中,三个关键字必须同时使用,才能达到异常处理的效果_____×__。
6.使用import 导入一包时,可以将这个包的子包也一并导入__×_____。
二、选择题1.异常是指___D____。
A.程序中的语法错误B.程序的编译错误C.程序执行过程中遇到的事先没有预料到的情况D.程序执行过程中遇到的事先没有预料到的情况,或程序事先定义好的可能出现的意外情况2.如果一个程序中有多个catch语句,程序会__C_____。
A.每个catch都会执行一次B.把每个符合条件的catch语句都执行一次C.找到适合的异常类型后就不再执行其它catch语句D.找到适合的异常类型后还要执行其它catch语句3.下列关于finally说法正确的是__C_____。
A.finally语句应该放在所有catch语句的前面B.finally语句应该放在所有catch语句的后面C.无论程序是否找到合适的catch匹配,都会去执行finallyD.如果程序在前面找到了多个适合的catch匹配,就不再执行finally语句了4.在一个方法内抛出异常时,应该使用下列哪个子句____A___。
A. throwB. catchC. finallyD. throws5.下列描述中,错误的一个是____B___。
A. 异常抛出点后的代码在抛出异常后不再执行B. 一个try代码段后只能跟有一个catch代码段C. try 一般要和catch联合使用D. 在编写程序过程中,要考虑对异常的处理6.一个catch语句段一定要和下列哪一项配合使用__A_____。
Java程序设计案例教程(第二版)周怡、张英主编。第12章 习题答案

习题12一、单选题1. 答案:B 难度:容易参考出处:12.1节2. 答案:D 难度:较难参考出处:12.1.1节3. 答案:B 难度:一般参考出处:12.1.1节4. 答案:C 难度:一般参考出处:12.2.1节5. 答案:C 难度:一般参考出处:12.2.3节6.答案:D 难度:较难参考出处:12.2.2节7.答案:B 难度:一般参考出处:12.1节8.答案:A 难度:一般参考出处:12.2.2节9.答案:C 难度:一般参考出处:12.2节二、填空题1. 答案:记录难度:一般参考出处:12.1.1节2. 答案:数据库难度:容易参考出处:12.1节3. 答案:数据库难度:容易参考出处:12.1节4. 答案:表难度:容易参考出处:12.2.1节5.答案:向导自定义难度:较难参考出处:12.2.3节6.答案:close()方法难度:容易参考出处:12.3.3节三、问答题1.Java是通过什么来访问数据库的?JDBC2.JDBC是什么?JDBC是JAVA系统提供给用户在JAVA程序中操纵数据库的Java API,可以为不同数据库提供统一访问,它是一组由Java语言编写的类和接口组成。
3.以JDBC-ODBC方式访问数据库时,如何加载驱动程序?用Class.forName(“驱动程序名”)这种方式4.简述JDBC-ODBC方式访问数据库的基本步骤。
首先设置数据源,然后用Class.forName(“驱动程序名”)加载驱动程序,再以DriverManager.getConnection()方法连接数据库,接着用连接对象的方法createStatement()创建SQL语句对象。
以上过程完成后即可执行实际的SQL语句对数据库进行操作。
最后,要关闭SQL语句对象和数据库连接。
四、判断题1.答案:X难度:容易参考出处:12.2.3节2.答案:√难度:容易参考出处:12.2.5节3.答案:√难度:容易参考出处:12.2.3节4.答案:√难度:容易参考出处:12.2.1节5.答案:X难度:容易参考出处:12.3.3节6. 答案:√难度:容易参考出处:12.3.3节五、程序设计题1. 打开Access,创建一个空的数据库PatientDatabase.mdb。
Java程序设计案例教程第二版周怡张英主编。第4章 Java流程操纵 课后习题答案
System.out.println(i);
System.out.println();
5.如果在程序执行过程中,while 语句中表达式的值始终为 true,则循环体会被无数次执
行,进入到无休止的____死循环___ 状态中。
6.for 语句的表达式 1 中可以并列多个表达式,但它们之间要用____逗号___ 隔开。
B.Hello
C.switch语句中case子句的语句序列中一定要包含break语句
D.switch 语句中 default 子句可以省略
6.执行 for(i=1;i<=10;i++)循环后,i 的值为___C___。
A.1
B.10
7.下列关于for循环和while循环的说法中__A___是正确的。
习题 4
一、选择题
1.下列语句执行后的输出结果是__A____。
if (6<2*5)
System.out.print("Hello");
System.out.print(" Every One");
A.Hello Every One
2.下列语句执行后,k 的值是__C____。
A.12
int i=6,j=8,k=10,m=7;
if (条件1) System.out.println("A");
Else if (条件2) System.out.println("B");
else System.out.println("C");
System.out.println(___"D"____); 8.设有以下程序段, 填写适当表达式,使程序运行时执行 3 次循环体。
java程序设计使用教程(第2版)参考答案
一、简答题
1.Java语言有哪些特点?主要用于能够哪些方面的软件开发?
特点:(1)面向对象,(2)平台无关性,(3)分布式,(4)可靠性和安全性,(5)多线程,(6)简单性,(7)健壮性,(8)高性能,(9)灵活性。
适用范围:(1)所有面向对象的应用开发,包括面向对象的事件描述、处理、综合等。(2)计算过程的可视化、可操作化的软件的开发。(3)动态画面的设计,包括图形图象的调用。(4)交互操作的设计。(5)Internet 的系统管理功能模块的设计,包括 Web 页面的动态设计、管理和交互操作设计等。(6)Intranet上的软件开发(直接面向企业内部用户的软件)。(7)与各类数据库连接查询的 SQL 语句实现。(8)网络通信与移动通信,网络集成方面。
// 1
// 1 1
// 1 2 1
// 1 3 3 1
// 1 4 6 4 1
// 1 5 10 10 5 1
public class XT00206 {
public static void main(String args[]) {
int i,j,temp;
int a[][]=new int[8][8];
JVM是运行Java程序必不可少的机制,编译后的Java程序指令并不直接在硬件系统上CPU上执行,而是由JVM执行。JVM是编译后的Java程序和硬件系统之间的接口,程序员可以把JVM看成一个虚拟的处理器,它不仅解释执行编译后的Java指令,而且还要进行安全检查,它是Java程序能在多平台间进行无缝移植的可靠保证,同时也是Java程序的安全检验引擎。
}//end speak()
}//end class
第二章习题答案
一、简答题
java语言程序设计教程第二版习题解答
习题一1.简述面向对象软件开发方法的重要意义。
【答】:面向对象的软件开发方法按问题论域来设计模块,以对象代表问题解的中心环节,力求符合人们日常的思维习惯,采用―对象+消息‖的程序设计模式,降低或分解问题的难度和复杂性,从而以较小的代价和较高的收益获得较满意的效果,满足软件工程发展需要。
2.解释下面几个概念:1)对象2)实例3)类 4)消息 5)封装 6)继承 7)多态【答】:1)对象:就是现实世界中某个具体的物理实体在计算机中的映射和体现,是由属性和操作所构成的一个封闭整体。
2)实例:是对象在计算机内存中的映像。
3)类:是描述对象的―基本原型‖,是描述性的类别或模板,即对一组对象的抽象。
它定义一组对象所能拥有的共同特征,用以说明该组对象的能力与性质。
4)消息:消息是对象之间进行通信的一种数据结构。
5)封装:封装性是保证软件部件具有优良的模块性的基础。
面向对象的类是封装良好的模块,类定义将其说明(用户可见的外部接口)与实现(用户不可见的内部实现)显式地分开,其内部实现按其具体定义的作用域提供保护。
6)继承:继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。
7)多态:多态性是指一个名字具有多种语义,即指同一消息为不同对象所接受时,可以导致不同的操作。
3.对象―汽车‖与对象―小汽车‖是什么关系,对象―汽车‖与―轮胎‖又是什么关系?【答】:对象―汽车‖与对象―小汽车‖具有继承关系,即对象―小汽车‖继承了对象―汽车‖。
―轮胎‖是对象―汽车‖的一个属性,所以对象―汽车‖包含―轮胎‖,二者是包含关系。
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架构模式每个章节的课后答案通常包括理论问题和编程练习题的解答。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
答:(1)常量名全部采用大写字母 (2)变量名、对象名、方法名、包名等标识符全部采用小写字母,如果标识符由多个单 词构成,则首字母小写,其后单词的首字母大写,其余字母小写,如 getName (3)类名首字母大写 难度:容易 参考出处: 3.8 节 2.Java 中的数据类型有哪些? 答:Java 语言中定义了 8 个基本数据类型,它们分别是字节型(byte) 、短整型(short) 、 整型 (int) 、 长整型 (long) 、 单精度浮点型 (float) 、 双精度浮点型 (double) 、 字符型 (char) 、 布尔型(boolean) 难度:容易 参考出处: 3.2 节 3.什么是常量?Java 中常量的定义有几种? 答: 常量是在程序中可以直接引用的实际数据项, 并且在所有的操作中其值始终保持不变。 在 Java 语言中,常量有整数类型、浮点类型、字符类型和布尔类型,这种表示方式的常量 称为直接常量。 常量除了使用这种表示方式以外, 还可以用标识符表示常量, 称为符号常量。 符号常量必须先声明,后使用。 难度:容易 参考出处: 3.4.1 节 4.请举例说明 Java 中数据类型的转换分为哪两种? 答:(1)自动类型转换是从低级数据类型向高级数据类型的转换。 例如: int x=8; long y=x; 虽然把 int 型数据赋值给 long 型变量, 但是 Java 进行了自动转换, 所以程序在编译的时 候不会出错。 (2) 强制类型转换是把数据从高级数据类型向低级数据类型转换。 例如: float x=58.2; int y=(int)c; 将浮点类型转换成整型类型时,整数部分值保留,小数部分值丢失,因此变量 y 的值为 58。 难度:容易 参考出处: 3.7 节 五、程序设计题 1.已知一个单精度浮点型的变量 x=12.34,分别求出它的整数部分和小数部分并显示出来。 答:public class Test1 { public static void main(String args[]) { float x=12.34f; int y=(int)(x); float z=(float)(x-y); System.out.println("x="+x); System.out.println("y="+y); System.out.println("z="+z); } }
5.已知摄氏温度转换成华氏温度的公式。
9 c 32 5 一个护士量得一个病人的体温是 37.8 摄氏度,求病人体温是华氏多少度? 答:public class Test5 { public static void main(String args[]) { double c=37.8; double f=(9.0/5.0)*c+32; System.out.println("c="+c); System.out.println("f="+f); } } f
习题 3
一、判断题 1.Java 的 各 种 数 据 类 型 占 用 固 定 长 度 , 与 具 体 的 软 硬 件 平 台 环 境 无 关 。 ( √ ) 难度:容易 参考出处: 3.2 节 2.用“+”可以实现字符串的拼接,用“-”可以从一个字符串中去除一个字符子串。(× ) 难度:容易 参考出处: 3.5 节 3.Java 不区分大小写的语言。(×) 难度:容易 参考出处: 3.1.1 节 4.Java 的 String 类的对象既可以是字符串常量,也可以是字符串变量。(√ ) 难度:容易 参考出处: 3.4 节 5.注释的作用是使程序在执行时在屏幕上显示//之后的内容。(√ ) 难度:容易 参考出处: 3.1.4 节 6.在 Java 的方法中定义一个常量要用 const 关键字。( × ) 难度:容易 参考出处: 3.4.1 节 二、选择题 1.Java 语言中语句是以 C 作为结束的。 A.句号 B.引号 C.分号 D.括号 2. 初次在医院进行挂号的患者需要提供其基本信息,其中年龄数据类型的定义形式为 A 。 A.int B.double C.char D.boolean 3.下面的 Java 的标识符哪个是合法的 A 。 A.$患者编号 B.患者 姓名 C.患者-年龄 D.1 患者婚否 4.关于数据类型转换,下面描述中错误的是 C 。 A.int 类型可以转换成 float 类型数据 B.long 类型可以转换成 short 类型数据 C.long 类型不可以转换成 short 类型数据 D.数据类型不一致时,必须进行数据类型的转换才能进行赋值 5.以下数据类型最高级的是 D 。 A.short B.int C.char D.float 6.设 int x = 1 , y = 2 则表达式 x+=++y 运行后 x 的值是 A 。 A.4 B.3 C.2 D.1 7.换行符的正确转义字符是 C 。 A./n B.\r C.\n D./r 三、填空题 1.整型类型的变量有字节型 、 短整型 、 整型 、 长整型 。 2.Java 中,逻辑常量的值有 true 和 false 。 3.表达式(15>20 ? 1 : 2)的值为 2 。 4.执行语句 int s=(int)123.45 之后,变量 s 的值为 123 。 5.现有 2 个 char 类型的变量 x='a',y=3,当执行 x=(char)(x+y);语句之后,x 的值应该是 100 。 6.Java 中定义常量必须使用的关键字是 final 。 四、简答题 1.标识符的定义规则有哪些?
System.out.println("a="+a); System.out.println("b="+b); System.out.println("c="+c); System.out.println("d="+d); System.out.println("e="+e); System.out.println("f=&知某位学生的语文、数学、英语的成绩是 87、72、93 分,求该生 3 门课程的总分和平 均分。 答:public class Test2 { public static void main(String args[]) { int x=87,y=72,z=93; int sum; float avg; sum=x+y+z; avg=sum/3; System.out.println("sum="+sum); System.out.println("avg="+avg); } } 3.已知圆的半径为 3.5 厘米,求圆的周长与面积。 答:public class Test3 { public static void main(String args[]) { double r=3.5; double l,s; l=2*3.14*r; s=3.14*r*r; System.out.println("l="+l); System.out.println("s="+s); } } 4.已知两个整型变量 x=20,y=3,分别求出两个数的加、减、乘、除、乘方,余数的值并显 示出来 答:public class Test4 { public static void main(String args[]) { int x=20,y=3; int a=x+y; int b=x-y; int c=x*y; double d=x/y; double e=Math.pow(x,y); int f=x % y;