java第四章课后习题答案
Java程序设计案例教程 习题答案 第4章 面向对象 下
第4章面向对象(下)一、填空题1. 12.重写3. final4. instanceof5. Implements6.编译时异常7. RuntimeException8.逗号二、判断题1.对2.对3.错4.对5.错6.对7.对8.错9.对10.错三、选择题1. B2. D3. D4. D5. B6. D7. C8. B9. B10.D11.C四、简答题1.抽象类和接口有如下区别:1)抽象类可以有构造方法,接口中不能有构造方法。
2)抽象类中可以有普通成员变量,接口中没有普通成员变量。
3)抽象类中可以包含非抽象的普通方法,接口中的所有方法必须都是抽象的,不能有非抽象的普通方法。
4)抽象类中的抽象方法的访问类型可以是public, protected和(默认类型),但接口中的抽象方法只能是public类型的,并且默认即为public abstract类型。
5)抽象类中可以包含静态方法,接口中不能包含静态方法。
6)抽象类和接口中都可以包含静态成员变量,抽象类中的静态成员变量的访问类型可以任意,但接口中定义的变量只能是public static final类型,并且默认为public static final类型。
7) 一个类可以实现多个接口,但只能继承一个抽象类。
2.在类的继承中需要注意的问题:1).在Java中,类只支持单继承,不允许多重继承,也就是说一个类只能有一个直接父类;2).多个类可以继承一个父类;3).在Java中,多层继承是可以的,即一个类的父类可以再去继承另外的父类;4).在Java中,子类和父类是一种相对概念,也就是说一个类是某个类父类的同时,也可以是另一个类的子类。
五、编程题1.Employee.java139//定义一个测试类140 public class Test{141public static void main(String[] args){142//声明一个Employee类型的数组,并创立不同子类型的对象143Employee [ ] employee = {new SalariedEmployee (“张三”,1,6000), newHourlyEmployee (“李四”,2,50,180) , new SalesEmployee (“王五” ,3, 6500,0・15),new BasePlusSalesEmployee(, 4,5000,0.15,2000)}; 144//打印每个员工的工资145for (int i = 0; i < employee.length ;i + + )146System.out.printin(Math.round(employee[i].getSalary(10)));147)148)。
JAVA第四章课后习题解答
txtFl1=new TextField(5); txtFl2=new TextField(5); txtFl3=new TextField(5); btn1=new Button("+"); btn2=new Button("-"); btn3=new Button("*"); btn4=new Button("÷");
public class Test4_9 extends Frame implements ActionListener{ Button btn; public Test4_9(){ super("弹出窗口练习"); setSize(300,200);
5
setVisible(true); setLayout(new BorderLayout());
TextField txtFl1,txtFl2,txtFl3;
2
Button btn; public Test4_6(){
super("简单加法运算器"); setSize(300,200); setVisible(true); setLayout(new FlowLayout());
txtFl1=new TextField(5); txtFl2=new TextField(5); txtFl3=new TextField(10); btn=new Button("=");
java_开发实战经典_第四章课后习题答案_完整版
第一题public class Four01 {public static double sum(int a){double sum =1;for(int i=1; i<=a;i++){sum = sum*i;}return sum;}public static void main(String[]args){int a =4;double sum = 0;double k[]=new double[a];for(int i=1; i<=4; i++){k[i-1] = sum(i);}for(int j=0;j<k.length;j++){sum = sum+k[j];}System.out.println("总数为:"+sum);}}第二题public static void main(String[]args){int a[]={1,2,3,4,5,6,7,8,9,10,11};int o=0,e=0;for(int i=0 ;i<a.length; i++){if(a[i]%2==0){e++;}else{o++;}}System.out.println("奇数个数为:"+o+"\t"+"偶数个数为:"+e); }}第三题public class Four03 {public static void main(String[]args){int oldArr[]= {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};int newArr[]=new int[16];for(int i=0,j=0;i<oldArr.length; i++){if(oldArr[i]!=0){newArr[j]=oldArr[i];j++;}}for(int i=0; i<newArr.length; i++){//必须要写这个if语句,因为newArr多余的空间默认值为0if(newArr[i]!=0)System.out.print(newArr[i]+" ");}}}第四题public class Four04 {public static void main(String[]args){ int Array[] = {1,2,3,4,5,6,7,8,9,10,11};int m = max(Array);System.out.println("最大值为:"+m);int a = min(Array);System.out.println("最小值为:"+a);int s = sum(Array);System.out.println("总数为:"+s);}public static int max(int temp[]){int z = temp[0];for(int i=0; i<temp.length; i++){if(z<temp[i]){z=temp[i];}}return z;}public static int min(int temp[]){int z=temp[0];for(int i=0; i<temp.length; i++){if(z>temp[i]){z=temp[i];}}return z ;}public static int sum(int temp[]){int sum =0;for(int i=0; i<temp.length; i++){sum = sum +temp[i];}return sum ;}}第五题public class Four05 {public static void main(String[]args){ int Array[]= {1,2,3,4,5,6,7,8,9,10,11};int a =5;int b = 100;search(a,Array);search(b,Array);}public static void search(int c,int temp[]){ boolean flag = false;for(int i=0; i<temp.length; i++){if(c == temp[i]){flag = true;}}if(flag){System.out.println("YES,此数组中存在元素"+c);}else{System.out.println("NO,此数组中不存在元素"+c);}}}第六题public class Four06 {public static void main(String[]args){int temp[] = new int[10];init(temp);print(temp);reserve(temp);System.out.println();print(temp);}public static void init(int x[]){for(int i=0; i<x.length; i++){x[i] = i;}}public static void print(int x[]){for(int i=0; i<x.length; i++){System.out.println(x[i]+"、");}}public static void reserve(int x[]){int foot =0;int head = 0;if(x.length%2 == 0){foot = x.length/2;head = foot-1;for(int i=0; i<x.length/2; i++){int temp =x[foot];x[foot] = x[head];x[head] = temp;foot++;head--;}}else{foot = x.length/2;head = foot ;for(int i=0; i<x.length/2+1; i++){int temp = x[foot];x[foot] = x[head];x[head] = temp;head--;foot++;}}}}第七题public class Four07 {public static void main(String args[]){float score[] = {90f,87f,78f,67f,93f,79f,82f,84f,71f,86f};float max = score[0];for(int i=0; i<score.length; i++){if(max<score[i]){max = score[i];}}System.out.println("最高分为:"+max);}}第八题public class Four08 {public static void main(String[] args){int Array[]={1,2,1,3,4,6,5,4,3,2,0,9,8,7,6,5,4,3,5,6,7,8,9,0,9,8,2,1,3,4,};int n1=0,n2=0,n3=0,n4=0,n5=0,n6=0,n7=0,n8=0,n9=0,n0=0;for(int i=0; i<Array.length; i++){switch(Array[i]){case 1:{n1++;break;}case 2:{n2++;break;}case 3:{n3++;break;}case 4:{n4++;break;}case 5:{n5++;break;}case 6:{n6++;break;}case 7:{n7++;break;}case 8:{n8++;break;}case 9:{n9++;break;}case 0:{n0++;break;}}}System.out.println("0---->9的个数分别为:"+n0+"、"+n1+"、"+ n2+"、"+n3+"、"+n4+"、"+n5+"、"+n6+"、"+n7+"、"+n8+"、"+n9);}}第九题public class Four09 {public static void main(String[] args){int a[]= {1,2,3,4,5,6,7,8,9,0};int maxFoot =0;int max = a[0];for(int i=0; i<a.length; i++){if(max<a[i]){max=a[i];maxFoot=i;}}int val = a[0];a[0] = a[maxFoot];a[maxFoot] = val;System.out.println(a[0]);}}第十题public class Four10 {public static void main(String[] args){int temp[]= {1,2,3,4,5,6,7,8,9,10};java.util.Arrays.sort(temp);print(temp);temp = inc(temp,13,12,34,5,6,7);java.util.Arrays.sort(temp);print(temp);}public static void print(int a[]){for(int i=0; i<a.length; i++){System.out.print(a[i]+"、");}System.out.println();}public static int[] inc(int a[],int...val){int value[] = new int[a.length+val.length];System.arraycopy(a,0,value,0,a.length);System.arraycopy(val,0 , value, a.length, val.length);return value;}}。
《软件职业技术学院“十一五”规划教材:Java编程基础》课后习题第四章答案
第一题:FloatToInt.javaimport javax.swing.JFrame;import javax.swing.JOptionPane;public class FloatToInt extends JFrame{/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub//输出消息提示框String str = JOptionPane.showInputDialog("请输入一个成绩:");//先将输入的浮点数(是String类型)转化成float类型float f = Float.parseFloat(str);//将浮点数强制转换成int型int score = (int) f;//创建一个FloatToInt对象,以便于调用makeWarning(String warning)方法FloatToInt a = new FloatToInt();//调用makeWarning(String warning)方法a.makeWarning("整数部分是:"+score);}//定义消息对话框makeWarning(String warning)方法public void makeWarning(String warning){JOptionPane.showMessageDialog(this, warning, "输出一个浮点数的整数部分", JOptionPane.PLAIN_MESSAGE);}}第二题Score.javaimport javax.swing.JFrame;import javax.swing.JOptionPane;public class Score extends JFrame{public static void main(String[] args){//输出消息提示框String str = JOptionPane.showInputDialog("请输入一个成绩:");//先将输入的浮点数(是String类型)转化成float类型float f = Float.parseFloat(str);//创建Score对象,以便于调用makeWarning(String warning)方法Score s = new Score();//如果大于60,及格if(f>=60){//调用Score对象的makeWarning(String warning)方法s.makeWarning("及格");}else{//不及格//调用Score对象的makeWarning(String warning)方法s.makeWarning("不及格");}}//定义消息对话框makeWarning(String warning)方法public void makeWarning(String warning){JOptionPane.showMessageDialog(this, warning, "判断是否及格", JOptionPane.WARNING_MESSAGE);}}第三题Rectangle.javapackage homework;//创建一个Rectangle类public class Rectangle {//定义成员变量:包括length和width属性float length=1f; //定义length属性,默认值为1float witdh=1f; //定义width属性,默认值为1//定义获取length属性的方法public float getLength() {return length;}//定义设置length属性的方法public void setLength(float length) {//判断矩形的长度是否大于20.0if(length>20.0f){System.out.println("该矩形的长大于20.0!");}else{System.out.println("该矩形的长小于20.0!");}this.length = length;}//定义获取width属性的方法public float getWitdh() {return witdh;}//定义设置width属性的方法public void setWitdh(float witdh) {//判断矩形的宽度是否大于20.0if(witdh>20.0f){System.out.println("该矩形的宽大于20.0!");}else{System.out.println("该矩形的宽小于20.0!");}this.witdh = witdh;}/*//定义构造方法,设置属性的默认值Rectangle(int length,int width){length =1;width =1;}*///定义计算矩形周长的方法perimeterpublic float perimeter(float length,float width){//定义一个表示周长的int型变量perimeterfloat perimeter;perimeter = (length+width)*2;return perimeter;}//定义计算矩形面积的方法areapublic float area(float length,float width){//定义一个表示面积的int型变量areafloat area;area = length*width;return area;}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub//创建一个Rectangle类的对象Rectangle r = new Rectangle();//调用计算矩形周长的perimeter方法(先获取对象r默认的属性值r.getLength(), r.getWitdh())float p = r.perimeter(r.getLength(), r.getWitdh());//调用计算矩形面积的area方法(先获取对象r默认的属性值r.getLength(), r.getWitdh())float area = r.area(r.getLength(), r.getWitdh());//打印输出该矩形的周长和面积System.out.println("该矩形的周长为:"+p+"\n 面积为:"+area);r.setLength(30.6f);r.setWitdh(13.5f);// 调用计算矩形周长的perimeter方法(先获取对象r默认的属性值r.getLength(), r.getWitdh())float p1 = r.perimeter(r.getLength(), r.getWitdh());// 调用计算矩形面积的area方法(先获取对象r默认的属性值r.getLength(), r.getWitdh())float area1 = r.area(r.getLength(), r.getWitdh());//打印输出该矩形的周长和面积System.out.println("该矩形的周长为:"+p1+"\n 面积为:"+area1);}}。
Java程序设计 第4章习题参考答案[2页]
第4章习题参考答案一、简答题1.Java提供了哪些数据类型,全部写出来。
整型:byte,short,int,long数值型浮点型:float,double基本数据类型字符型:char数据类型布尔型:boolean类:class复合数据类型字符串:String接口:interface2.如何进行数据类型的转换?有2种方式:自动类型转换:运算时,不同类型的数据先转换成同一类型后再参与运算,转换的原则是位数少的类型转换成位数多的类型,由系统自动处理。
强制类型转换:当位数多的类型向位数少的类型进行转换时,需要用户明确说明要转换的类型,需要用户在程序中指明。
3.类的修饰符有哪些?有什么区别?类的修饰符包括访问控制修饰符、静态修饰符static、最终说明符final。
访问控制修饰符包括4种类型:privat、default、protected、public。
用static声明的成员变量被视为类的成员变量,而不能当成实例对象的成员变量,也就是说,静态变量是类固有的,可以被直接引用,而其它成员变量声明后,只有生成对象时才能被引用。
4.public的类和abstract的类有什么不一样?public的类是公共类,可以被继续,可以实例化,可以被其他包访问。
abstract的类是抽象类,其中一定含有抽象方法,abstract class的子类在继承它时,对非抽象方法既可以直接继承,也可以覆盖;而对抽象方法,可以选择实现,也可以通过再次声明其方法为抽象的方式,无需实现,留给其子类来实现,但此类必须也声明为抽象类。
5.什么是最终类?如何声明?最终类不能被继承,也没有子类。
final类中的方法默认是final的。
final方法不能被子类的方法覆盖,但可以被继承。
final成员变量表示常量,只能被赋值一次,赋值后值不再改变。
声明方法:final class ClassName。
二、操作题1.创建一个学生类Student,包括学号no、姓名name、年龄age、性别sex四个属性以及学习study、实践practice两个方法。
JAVA课后的答案第四章
第4章1.假定乘坐飞机时,每位顾客可以免费托运20kg以内的行李,超过部分按每公斤收费1.2元,以下是相应的计算收费程序。
该程序存在错误,请找出。
public class Test{public static void main(String[] args) throws IOException{float w,fee;//以下代码为通过控制台交互输入行李重量InputStreamReader reader=new InputStreamReader(System.in);BufferedReader input=new BufferedReader(reader);System.out.println("请输入旅客的行李重量:");String temp=input.readLine();w = Float.parseFloat(temp); //字符串转换为单精度浮点型fee = 0;if ( w > 20);fee = (float)1.2 * (w-20);System.out.println("该旅客需交纳的托运费用:"+fee+"元");}}缺少import java.io.*; 语句2.有一条长的阶梯,如果每步2阶,则最后剩1阶,每步3阶则剩2阶,每步5阶则剩4阶,每步6阶则剩5阶,只有每步7阶的最后才刚好走完,一阶不剩,问这条阶梯最少共有多少阶?找出以下求解程序的错误所在。
public class Test{ public static void main(String[] args){int i;while(i%2==1&&i%3==2&&i%5==4&&i%6==5&&i%7==0) {i++;}System.out.println("这条阶梯最少有:"+i+"阶");}}1)变量i应进行初始化。
047Java入门经典第4章课后习题答案
3
Java 入门经典第 4 章课后习题答案
4.7 习题
选择题
1.当编译和运行下列代码时会发生什么?( BE ) public class Test { public static void main(String[] args) { char myChar='c'; switch (myChar){ default: case'a': System.out.println("a"); break; case'b': System.out.println("b"); break; } } } A.switch 块非法,因为只能使用 int 类型作为参数 B.switch 块合法 C.switch 块非法,因为 default 必须放在块的结尾处 D.运行程序后,控制台无输出 E.运行程序后,控制台输出 a 2.当编译和运行下列代码时会发生什么?( BD ) public class Test { public static void main(String[] args) { int i=5; do { System.out.println(i); }while (--i>5); System.out.println("Finished"); } }
1Байду номын сангаас
A.6
B.5
C.4
D.Finished
3.当编译和运行下列代码后输出的结果是 Second,则 x 的取值范围是?( D ) public class Test { public static void main(String[] args) { int x=( if (x>0) System.out.println("First"); else if (x>-3) System.out.println("Second"); else System.out.println("Third"); } } A.x>0 B.x<=0 C.x<-3 D.x<=0 且 x>-3 4.当编译和运行下列代码时会发生什么?( C ) public class Test { public static void main(String[] args) { boolean flag=false; if(flag=true) { System.out.println("true"); }else{ System.out.println("false"); } } } A.编译错误 B.运行错误 C.输出 true D.输出 false 解析:注意 if(flag=true),若为 if(flag==true),则结果为 D 5. .当编译和运行下列代码时会发生什么?( C ) public class Test { public static void main(String[] args) { int total=0; for(int i=0;i>total;i++) { System.out.println(i); } System.out.println(total); } }
java程序设计基础 第3版 课后习题解答 第四章
Java第四章课后习题解答:1.//filename: App4_1.javaimport java.io.*;public class App4_1{public static void main(String[] args)throws IOException{ float score;String str;BufferedReader buf=new BufferedReader(new InputStreamReader (System.in));System.out.println("请你输入一个成绩: ");str=buf.readLine();score=Float.parseFloat(str);int grade=(int)score/10;switch(grade){case 10:case 9: System.out.println(" 优");break;case 8: System.out.println(" 良");break;case 7: System.out.println(" 中");break;case 6: System.out.println(" 及格");break;default: System.out.println(" 不及格");}}}2.//filename: App4_2.javaimport java.io.*;public class App4_2{public static void main(String[] args){int score;int grade;char result;Scanner b = new Scanner(System.in);score = b.nextInt();grade = score / 10;switch(grade)case 10:case 9:case 8: result = 'A';break;case 7: result = 'B';break;case 6: result = 'C';break;default: result = 'D';break;}System.out.println(result);}}3.//filename: App4_3.javapublic class App4_3{public static void main(String[] args) {int i;for( i=1;i<=100;i++){if(i%3==0 && i%7==0)System.out.println("i="+i);}}}4.//filename: App4_4.javapublic class App4_4{public static void main(String[] args) {int i,n;int s=0;for(i=1,i<=n,i++)n=i*n;s=s+n;System.out.println("s="+s);}}//filename: App4_5.javaimport java.util.*;public class App4_5{public static void main(String arg[]){Scanner insert=new Scanner(System.in);int n;System.out.print("请输入一个数字n:");n = insert.nextInt();double b=1;double e=1;double f=1;double g= (-1);double sum=0;for (int i=1; i <= n ; i++ ){e=e*i;b=( 1 / e );g = g*(-1);f=b*g;sum=sum+f;}System.out.println("sum=1!-(1/2!)+(1/3!)-(1/4!)+......-((-1)^(n-1))*(1/n!)="+sum); }}6.//filename: App4_6.javapublic class App4_6{public static void main(String[] args){for(int i=100; i<1000; i++){int gw = i%10;int sw = i/10%10;int bw = i/100;int gl=g*g*g;int sl=s*s*s;int bl=b*b*b;int s = gl+sl+bl;boolean eq = s==i;if(eq)System.out.println(i+"="+bw+"^3+"+sw+"^3+"+gw+"^3"); }}}}7.//filename: App4_7.javaimport java.util.*;public class App4_7{public static void main(String[] args){int x,s=0;System.out.print("请输入你需要的整数:");Scanner scan=new Scanner(System.in);x=scan.nextInt();for(int i=1;i<x;i++){if(x%i==0){s=s+i;}els{continue;}}if(s==x){System.out.println(x+"是完全数");}else{System.out.println(x+"不是完全数");}}}8.//filename: App4_8.javaimport java.util.*;public class App4_8{public static void main(String[] args){String n;int d,x;int m,end=0,sum=0;System.out.print("请输入一个数:");Scanner scan=new Scanner(System.in);n=scan.nextLine();d=n.length();x=Integer.parseInt(n);for (int i=1; i<=d;i++ ){m=x%10;x=x/10;end=end+m;}System.out.println(end);}}9.//filename: App4_9.javaimport java.util.*; public class App4_9 {public static void main(String arg[]){Scanner insert=new Scanner(System.in);float i;int j;float k;System.out.print("输入一个浮点型数字:");i = insert.nextFloat();j = (int)i;k = i-j;System.out.println("输入的数字的整数部分:"+j);System.out.println("输入的数字的小数部分:"+k);}}10.//filename: App4_10.javapublic class App4_10{public static void main(String arg[]){double x=3000;int y=0;while (x >= 5 ){x *= 0.5;y += 1;}System.out.println("需要"+y+"天,绳子的长度会短于米"); }}11.//filename: App4_11.javapublic class App4_11{public static void main(String arg[]){int q;int h = 1;for (int i= -1 ; i <= 4 ; i++ ){h = h + i;q = h;System.out.println();for (int j=i+2 ; j <= 5 ; j++ ){System.out.print((q=q+j)+"\t");}}}}。
Java第四章作业答案
习题四一、问答题1.子类可以有多个父类吗?答:Java不支持多重继承(子类只能有一个父类)2.如果子类和父类不在同一个包中,子类是否继承父类的友好成员?答:不能。
子类对父类可以访问同一个包中的父类的友好成员,不能访问其它包中父类的友好成员。
3.子类怎样隐藏继承的成员变量?答:子类中声明的成员变量和父类中成员变量同名时,子类就隐藏了继承的成员变量4.子类重写方法的规则是怎样的?重写方法的目的是什么?答:子类重写的方法的返回值类型,方法名,参数类型,顺序,个数都要与父类继承的方法相同,而且访问修饰符的限定范围大于等于父类方法。
目的是可以父类的状态和行为改变为自身的状态和行为,实现多态。
5.父类的final方法可以被子类重写吗?答:不可以6.什么类中可以有abstract方法?答:.abstract类。
abstract方法必须在abstract类中,而abstract类中可以没有abstract 方法7.一个类的各个子类是怎样体现多态的?答:通过重写方法二、选择题1.下列哪个叙述是正确的? CA.子类继承父类的构造方法。
B.abstract类的子类必须是非abstract类。
C.子类继承的方法只能操作子类继承和隐藏的成员变量。
D.子类重写或新增的方法也能直接操作被子类隐藏的成员变量。
2.下列哪个叙述是正确的? DA.final 类可以有子类。
B.abstract类中只可以有abstract方法。
C.abstract类中可以有非abstract方法,但该方法不可以用final修饰。
D.不可以同时用final和abstract修饰同一个方法。
E.允许使用static修饰abstract方法。
3.下列程序中注释的哪两个代码(A,B,C,D)是错误的(无法通过编译)?CDclass Father {private int money =12;float height;int seeMoney(){116return money ; //A}}class Son extends Father {int height;int lookMoney() {int m = seeMoney(); //Breturn m;}}class E {public static void main(String args[]) {Son erzi = new Son();erzi.money = 300; //Cerzi.height = 1.78F; //D}}注:money是Father的私有变量,是无法继承的,不能够赋值。
java_开发实战经典_第四章课后习题答案_完整版.doc
for(inti=0; i<score.length; i++){
if(max<score[i]){
max = score[i];
}
}
System.out.printin (”最分为:n+max);
}
}
第八题
public classFour08 {
public static voidmain(String[] args){
switch(Array[i] ) {
case1:{
nl++;
break;
}
case2:{
n2 + +;
break;
}
case3:{
n3 + + ;
break;
}
case4:{
n4++;
break;
}
case5:{
n5++;
break;
}
case6:{
n6++;
break;
}
case7:{
n7 + + ;
}
}
第二题
public static voidmain(String[]args){
inta[]={1,2,3,4,5.6,7,8,9,10,11};
int0=0,e=0;
for(inti=0 ;•丄ength; i++){
if(a[i]%2==0){
e++;
}else{
o++;
}
}
System,out.printIn("奇数个数为:”+o+”\t” + ”偶数个数为:”+e);
JAVA程序设计教程第四章参考答案
import java.util.*;public class Person{private String name;private char sex;private int year,month;public Person( ){}public Person(String nm,char sx,int y,int m) {name=nm;sex=sx;year=y;month=m;}public void printPerson( ) {Calendar now=Calendar.getInstance();int age=now.get(Calendar.YEAR)-year;System.out.println("Name: "+name+",Sex: "+sex+", Age: "+age);}public static void main(String args[]){Person pe1=new Person("Tom",'m',1980,10);pe1.printPerson();}}2.public class Rectangle{double width,length,girth,area;public Rectangle(){};public Rectangle(double wd,double le) {width=wd;length=le;}public void setWidth(double wd) {width=wd;}public void setLength(double le) {length=le;}public double getWidth( ) {return width;}public double getLength( ) {return length;}public double girth(){return 2*(width+length);public double area(){return width*length;}public void printRectangle(){System.out.println("Width="+width+" ,Length="+length);}public static void main(String args[]){Rectangle re1=new Rectangle(10,20);Rectangle re2=new Rectangle();re2.setWidth(3);re2.setLength(4);re1.printRectangle();System.out.println("Girth="+re1.girth()+",Area="+re1.area());re2.printRectangle();System.out.println("Girth="+re2.girth()+",Area="+re2.area());}}3.public class Matrix{private int mx[][],m,n;public Matrix(int r,int c) {m=r;n=c;mx=new int[m][n];iniMatrix();}public Matrix(){m=3;n=3;mx=new int[3][3];iniMatrix();}public void iniMatrix(){int i,j;for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mx[i][j]=(int)(Math.random()*100);}public void tranMatrix(){int i,j,t;int mt[][]=new int[m][n];for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mt[i][j]=mx[i][j];t=m;m=n;n=t;mx=new int[m][n];for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mx[i][j]=mt[j][i];}public void printMatrix(){int i,j;for(i=0;i<=m-1;i++){for(j=0;j<=n-1;j++)System.out.print(" "+mx[i][j]);System.out.println();}}public void addMatrix(Matrix b) {int i,j;for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mx[i][j]=mx[i][j]+b.mx[i][j];}public static void main(String args[]){Matrix ma=new Matrix(4,3);Matrix mb=new Matrix(4,3);System.out.println("The matrix_A:");ma.printMatrix();System.out.println("The matrix_B:");mb.printMatrix();System.out.println("Matrix_A + Matrix_B:");ma.addMatrix(mb);ma.printMatrix();System.out.println("Transpose Matrix_B:");mb.tranMatrix();mb.printMatrix();}}4.public class Substring{public static void main(String args[]){String str1=new String("addActionListener");String str2=new String("Action");int n;n=str1.indexOf(str2);if(n>=0){System.out.println("String_2 is in String_1");System.out.println("The substring before String_2 is "+str1.substring(0,n));System.out.println("The substring behind String_2 is "+str1.substring(n+str2.length( )));}}}五、写出程序运行后的结果1.2.。
java语言程序设计第4章-习题参考答案
第4章习题解答1.声明一个数组,保存一个学生的数学、语文、英语、物理、化学等课程的成绩,编写一个程序,计算5门课程的平均成绩,精确到0.1分,成绩值从键盘录入。
import java.util.Scanner;public class XT_1_score {public static void main(String[] args) {// TODO Auto-generated method stubdouble score[] = new double[5];System.out.println("请分别输入数学、语文、英语、物理、化学的成绩(数字之间用空格格开):");double sum = 0, average = 0;Scanner in = new Scanner(System.in);int i;for (i = 0; i < 5; i++)score[i] = in.nextDouble();for (i = 0; i < 5; i++)sum += score[i];average = sum / 5;System.out.println("平均成绩为:" + String.format("%.1f", average));}2.编程实现统计50名学生的百分制成绩中各分数段的学生人数,即:分别统计出100分、90-99分、80-89分、70-79分、60-69分、不及格的学生人数。
import java.util.Scanner;public class XT_2_score_sore {public static void main(String[] args) {// TODO Auto-generated method stubdouble score[] = new double[50];int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, i;System.out.println("请依次输入50名学生的成绩(用空格隔开):");Scanner br = new Scanner(System.in);for (i = 0; i < 50; i++)score[i] = br.nextDouble();for (i = 0; i < 50; i++) {if (score[i] == 100)a++;if (score[i] >= 90 && score[i] <= 99)b++;if (score[i] >= 80 && score[i] <= 89)c++;if (score[i] >= 70 && score[i] <= 79)d++;if (score[i] >= 60 && score[i] <= 69)e++;if (score[i] < 60)f++;}System.out.println("成绩为100分的个数:" + a);System.out.println("成绩为90-99分的个数:" + b);System.out.println("成绩为80-89分的个数:" + c);System.out.println("成绩为70-79分的个数:" + d);System.out.println("成绩为60-69分的个数:" + e);System.out.println("成绩为不及格的个数:" + f);}}3.编写一个程序,实现打印输出字符串数组中最大值和最小值。
自考教材《JAVA语言程序设计(一)》第四章习题解答
4.2 举例说明如何声明、创建和初始化多维数组。
声明二维数组:类型 数组名[ ][ ] 类型[ ][ ]数组名 类型[ ]数组名[ ] 例如: 声明 Sting subStr[ ][ ]; String [ ] [ ] subStr; String[ ] subStr[ ]; 创建 (1)String subStr[ ][ ]=new String[3][5];(直接分配,平衡数组) (2)String subStr[ ][ ]=new String[3][ ];(从最高维开始对每一维分配不等长空间,非 平衡数组) subStr[0]=new String[4];//第 1 个子数组有 4 个元素 subStr[1]=new String[5];//第 2 个子数组有 5 个元素 subStr[2]=new String[2];//第 3 个子数组有 2 个元素 (3)int[ ][ ] x={{5,6,7},{8,9,10,11},{18,19,10,10},{2,98}};//直接赋值创建 初始化:数组创建后,如果没有初始化,则根据类型 java 会自动赋予默认值。一般用循环 语句对其动态初始化,例如,以下循环给三维整型数组 aa 初始化为三角数组。 int a[]=new int[5]; int aaa[][][]=new int [4][3][3]; for (int i=0;i<a.length;i++) { a[i]=i+1; } for (int i=0;i<aaa.length;i++) { for (int j=0;j<aaa[i].length;j++) { for (int k=0;k<aaa[i][j].length;k++) { aaa[i][j][k]=(i+j+1)*(k+1);} } }
《Java语言程序设计(基础篇)》(第10版梁勇著)第四章练习题答案
Java 语言程序设计(基础篇)》(第10版梁勇著)第四章练习题答案4.1public class Exercise04_01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the length from the center to a vertex: "double r = input.nextDouble();double side = 2 * r * Math.sin(Math.PI / 5);double area = 5 * side * side / Math.tan(Math.PI / 5) / 4;System.out.println( "The area of the pentagon is " + area);}}4.1附加public class Exercise04_01Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the mass of the cart: " );double m = input.nextDouble();System.out.print( "Enter the force to push the cart: " );double F = input.nextDouble();final double PI = 3.14159;final double g = 9.8;double theta = Math.toDegrees(Math.asin(F / (m * g)));4.2public class Exercise04_02 {public static void main(String[] args) {);System.out.println(}"The angle of the ramp is + theta + " degrees );System.out.print("Enter point 1 (latitude and longitude) in degrees: " );double x1 = input.nextDouble();double y1 = input.nextDouble();System.out.print("Enter point 2 (latitude and longitude) in degrees: " );double x2 = input.nextDouble();double y2 = input.nextDouble();double d = 6371.01 * Math.acos(Math.sin(Math.toRadians(x1)) *Math.sin(Math.toRadians(x2)) +Math.cos(Math.toRadians(x1)) * Math.cos(Math.toRadians(x2)) *Math.cos(Math.toRadians(y1 - y2)));System.out.println("The distance between the two points is " + d + "km" );}} 4.2 附加public class Exercise04_02Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the mass of the cart: " );double m = input.nextDouble();System.out.print( "Enter the ramp angle: " );double theta = input.nextDouble();final double PI = 3.14159;final double g = 9.8;double F = m * g * Math.sin(Math.toRadians(theta));System.out.println("The force to push the cart is " + F + " Newtons" );}} 4.3public class Exercise04_03 {public static void main(String[] args) {double x1 = 35.2270869 * Math.PI / 180, y1 = -80.8431267 * Math.PI / 180; Scanner input =new Scanner(System.in);double x2 = 32.0835407 * Math.PI / 180, y2 = -81.0998342 * Math.PI / 180;// Savannahdouble x3 = 28.5383355 * Math.PI / 180, y3 = -81.3792365 * Math.PI / 180;// Orlandodouble x4 = 33.7489954 * Math.PI / 180, y4 = -84.3879824 * Math.PI / 180;// Atlantadouble d1 = 6371.01 * Math.cos(Math.sin(x1) * Math.sin(x2) +Math.cos(x1) * Math.cos(x2) * Math.cos(y1 - y2));double d2 = 6371.01 * Math.cos(Math.sin(x3) * Math.sin(x2 ) +Math.cos(x3) * Math.cos(x2) * Math.cos(y3 - y2));double d3 = 6371.01 * Math.cos(Math.sin(x3) * Math.sin(x4 ) +Math.cos(x3) * Math.cos(x4) * Math.cos(y3 - y4));double d4 = 6371.01 * Math.cos(Math.sin(x1) * Math.sin(x4 ) +Math.cos(x1) * Math.cos(x4) * Math.cos(y1 - y4));double d5 = 6371.01 * Math.cos(Math.sin(x4) * Math.sin(x2 ) +Math.cos(x4) * Math.cos(x2) * Math.cos(y4 - y2));double s = (d1 + d4 + d5) / 2;double area1 = Math.sqrt(s * (s - d1) * (s - d4) * (s - d5));s = (d2 + d3 + d5) / 2;double area2 = Math.sqrt(s * (s - d2) * (s - d3) * (s - d5));System.out.println( "The area is " + (area1 + area2) + " square kilometers" );}}4.3附加public class Exercise04_03Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the coefficient of friction: " );double u = input.nextDouble();double theta = Math.toDegrees(Math.atan(u));System.out.println( "The minimal angle for the brick to slide is " + theta4.4public class Exercise04_04 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the side: " );double side = input.nextDouble();// Compute the areadouble area = 6 * side * side / Math.tan(Math.PI / 6) / 4;System.out.println( "The area of the hexagon is " + area);}}4.4附加public class Exercise04_04Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the coefficient of friction: " );double u = input.nextDouble();System.out.print( "Enter the angle: " );double theta = input.nextDouble();final double PI = 3.14159;final double g = 9.8;double a = g * (Math.sin(Math.toRadians(theta)) -u * Math.cos(Math.toRadians(theta)));if (a <= 0)System.out.println( "The brick does not move or move at a constantspeed" );elseSystem.out.println( "The brick accelerates at " + a +" meters per square seconds" );}}4.5public class Exercise04_05 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the number of sidesSystem.out.print( "Enter the number of sides: " );int numberOfSides = input.nextInt();System.out.print( "Enter the side: " );double side = input.nextDouble();double area = numberOfSides * side * side / Math.tan(Math.PI / numberOfSides) / 4;System.out.println( "The area of the polygon is " + area);}}4.5附加public class Exercise04_05Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter a string: " );String s = input.nextLine();if (s.length() > 0)System.out.println( "The last character is " + s.charAt(s.length() -1));elseSystem.out.println( "An empty string" );}}4.6public class Exercise04_06 {public static void main(String args[]) { double r = 40;System.out.println( "Three random points are " );double angle = Math.random() * 360;double x = r * Math.cos(angle * Math.PI / 180);double y = r * Math.sin(angle * Math.PI / 180);System.out.println( "(" + x + ", " + y + ")" );angle = Math.random() * 360;x = r * Math.cos(angle * Math.PI / 180);y = r * Math.sin(angle * Math.PI / 180);System.out.println( "(" + x + ", " + y + ")" );angle = Math.random() * 360;x = r * Math.cos(angle * Math.PI / 180);y = r * Math.sin(angle * Math.PI / 180);System.out.println("(" + x + ", " + y + ")" );}} 4.6 附加public class Exercise04_06Extra {public static void main(String[] args) {Scanner input =new Scanner(System.in); System.out.print( "Enter a four-digit binary string: " ); String s = input.nextLine();Please enter exactly four binary digits '0' ); '0' ) * 2; '0' ) * 2 * 2; '0' ) * 2 * 2 * 2; 4.7public class Exercise04_07 {public static void main(String args[]) {java.util.Scanner input =new java.util.Scanner(System.in); System.out.print( "Enter the radius of the bounding circle: " ); double radius = input.nextDouble();System.out.println( "The coordinates of five points on the pentagon are"if (s.length() !=4)System.out.println(else {int value = 0;value+= (s.charAt(3) -value+= ); System.out.println(}} "The decimal number for + s + " is " + value););double angle = Math.PI / 2 - 2 * Math.PI / 5;double x = radius * Math.cos(angle);double y = radius * Math.sin(angle);System.out.printf( "(%.2f, %.2f)\n" , x, y);angle += 2 * Math.PI / 5;x = radius * Math.cos(angle);y = radius * Math.sin(angle);System.out.printf( "(%.2f, %.2f)\n" , x, y);angle += 2 * Math.PI / 5;x = radius * Math.cos(angle);y = radius * Math.sin(angle);System.out.printf( "(%.2f, %.2f)\n" , x, y);angle += 2 * Math.PI / 5;x = radius * Math.cos(angle);y = radius * Math.sin(angle);System.out.printf( "(%.2f, %.2f)\n" , x, y);angle += 2 * Math.PI / 5;x = radius * Math.cos(angle);y = radius * Math.sin(angle);System.out.printf( "(%.2f, %.2f)\n" , x, y);} }4.7附加public class Exercise04_07Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter a decimal number between 0 and 15: " );int value = input.nextInt();String s = "" ;int temp = value;s = temp % 2 + s;temp = temp / 2;s = temp % 2 + s;temp = temp / 2;s = temp % 2 + s;temp = temp / 2;s = temp % 2 + s;System.out.println( "The binary number for " + value + " is+ s); }}4.8public class Exercise04_08 {public static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter an ASCII codeSystem.out.print( "Enter an ASCII code: " );int code = input.nextInt();// Display resultSystem.out.println( "The character for ASCII code "+ code + " is " + ( char )code);} }4.9public class Exercise04_09 {public static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter an ASCII codeSystem.out.print( "Enter a character: " );char ch = input.next().charAt(0);// Display result System.out.println( + ( int )ch);"The Unicode for the character + ch + " is4.10 public class public staticString set1 = " 1 3 5 7\n"" 9 11 13 15\n""17 19 21 23\n""25 27 29 31"String set2 =" 2 3 6 7\n""10 11 14 15\n""18 19 22 23\n""26 27 30 31"String set3 =" 4 5 6 7\n""12 13 14 15\n""20 21 22 23\n""28 29 30 31"String set4 =" 8 9 10 11\n""12 13 14 15\n""24 25 26 27\n""28 29 30 31"String set5 ="16 17 18 19\n""20 21 22 23\n""24 25 26 27\n""28 29 30 31"int day = 0;// Create a Scanner Scanner input = Exercise04_10{ voi d main(String[]args) {new Scanner(System.in)// Prompt the user to answerquestions System.out.prin t( Is your birthday inSet1?\n );System.out.print(set1);System.out.print( "\nEnter 0 for No and 1 for Yes: ");char answer = input.next().charAt(0);if (answer == 'Y' )day += 1;// Prompt the user to answer questionsSystem.out.print( "\nIs your birthday in Set2?\n" ); System.out.print(set2);System.out.print( "\nEnter 0 for No and 1 for Yes: ");answer = input.next().charAt(0);if (answer == 'Y' )day += 2;// Prompt the user to answer questionsSystem.out.print( "Is your birthday in Set3?\n" ); System.out.print(set3);System.out.print( "\nEnter 0 for No and 1 for Yes: ");answer = input.next().charAt(0);if (answer == 'Y' )day += 4;// Prompt the user to answer questionsSystem.out.print( "\nIs your birthday in Set4?\n" ); System.out.print(set4);System.out.print( "\nEnter 0 for No and 1 for Yes: ");answer = input.next().charAt(0);if (answer == 'Y' )day += 8;// Prompt the user to answer questionsSystem.out.print( "\nIs your birthday in Set5?\n" ); System.out.print(set5);System.out.print( "\nEnter 0 for No and 1 for Yes: ");answer = input.next().charAt(0);if (answer == 'Y' ) day += 16;System.out.print ln( "\nYour birthdayis+ day+!" );4.11public class Exercise04_11 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter a decimal value (0 to 15): " );int decimal = input.nextInt();if (decimal > 15 || decimal < 0)System.out.println(decimal + " is an invalid input" );else if (decimal < 10)System.out.println( "The hex value is " + decimal);elseSystem.out.println( "The hex value is " + ( char )( 'A' + decimal10)); }}4.12public class Exercise04_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter a hex character: " );char hex = input.nextLine().charAt(0);String result = "" ;switch (hex) {case '0' : result = "0" ; break ;break ;case '1' : result = 1;;case '2' : result = "10" ; break ;case '3' : result = "11" ; break ;case '4' : result = "100" ; break ;case '5' : result = "101" ; break ;case '6' : result = "110" ; break ;case '7' : result = "111" ; break ;case '8' : result = "1000" ; break ;case '9' : result = "1001" ; break ;case 'A' : result = "1010" ; break ;case 'B' : result = "1011" ; break ;case 'C' : result = "1100" ; break ;case 'D' : result = "1101" ; break ; case 'E' : result ="1110" ; break ;case 'F' : result = "1111" ; break ; defaul tSystem.out.println(he x+ " is an invalid input" ); System.exit(1);System.out.println( } }4.13public class Exercise04_13 {public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a letter: ");char letter = input.nextLine().charAt(0);4.14public class Exercise04_14 {public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a letter grade: ");char grade = input.nextLine().charAt(0);int value = 0;if (Character.toUpperCase(grade) == 'A' )value = 4;else if (Character.toUpperCase(grade) == 'B' )value = 3;else if (Character.toUpperCase(grade) =='C' )"The binary value is " + result);if (Character.toUpperCase(letter) ==== 'E' || Character.toUpperCase(letter)==|| Character.toUpperCase(letter) == Character.toUpperCase(letter) ==System.out.println(letter + else if(Character.isLetter(letter))System.out.println(letter + elseSystem.out.println(letter +'A' ||Character.toUpperCase(letter)'I' 'O' ||'U' )" is a vowel" );" is a consonant" );value = 2;else if (Character.toUpperCase(grade) == value = 1; else if (Character.toUpperCase(grade) == 'F' )value = 0; else { System.out.println(grade + " is an invalid grade" System.exit(1); } System.out.println("The numeric value for grade " + " is " + value); } } 4.15public class Exercise04_15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print( "Enter an uppercase letter: " ) char ch = input.nextLine().charAt(0); int number = 0; switch (Character.toUpperCase(ch)) {'D' ) );+ gradecase 'A'case 'B'case 'C' : number = 2;breakcase 'D'case 'E'case 'F' : number = 3;breakcase 'G'case 'H'case 'I' : number = 4;breakcase 'J'case 'K'case 'L' : number = 5;breakcase 'M'case 'N'case 'O' : number = 6; breakcase 'P'case 'Q'case 'R'case 'S' : number = 7; breakcase 'T'case 'U'case 'V' : number = 8; breakcase 'W'case 'X'case 'Y'case 'Z' : number = 9; breakdefault : System.out.println(ch + "is an invalid input " );System.exit(1);}System.out.println( "The corresponding number is " + number);}}4.16public class Exercise04_16 {public static void main(String args[]) {char ch = ( char )(Math.random() * 26 + 'A' );System.out.println( "A random uppercase letter is " + ch);}}4.17public class Exercise04_17 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter a year: " );int year = input.nextInt();System.out.print( "Enter a month (first three letters with the first letterin uppercase): " );String month = input.next();if (month.equals( "Jan" ) || month.equals( "Mar" ) || month.equals( "May" )|| month.equals( "Jul" ) || month.equals( "Aug" ) || month.equals( "Oct" ) || month.equals( "Dec" ))System.out.print(month + " " + year + " has 31 days" );else if (month.equals( "Apr" ) || month.equals( "Jun" ) || month.equals( "Sep" ) || month.equals( "Nov" ))System.out.print(month + + year+has 30 days" );else if (month.equals( "Feb" )) if ((year % 4 == 0 && year %100 != 0) || (year % 400 == 0))System.out.print(month + else System.out.print(month + else System.out.print(month + } }4.18public class Exercise04_18 {public static void main(String[] args) {Scanner input = new Scanner(System.in); System.out.print( "Enter twocharacters: ");String s = input.nextLine();if (s.charAt(0) == System.out.print( else if(s.charAt(0) ==System.out.print(else if (s.charAt(1)==System.out.print(else {System.out.println( Syst em.exit(1); }if (s.charAt(1) == System.out.println( else if (s.charAt(1) == System.out.println( else if (s.charAt(1)==System.out.println( else if (s.charAt(1)==System.out.println(else{System.out.println(System.exit(2); 'M' )"Mathematics " );'C' )"Computer Science "); 'I' )"Information Technology " "Input major code" )'1' )"Freshman" );'2' )" " + year + " has 29days"" " + year + " has 28days"););););"Input status code" );"Sophomore" );'3' ) "Junior" );'4' ) "Senior" );4.19public class Exercise04_19 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the first 9 digits of an ISBN as integer: " );String number = input.nextLine();if (number.length() != 9) {System.out.println( "You need to enter exactly 9 digits" );System.exit(1);}// Calculate checksum (You may write a loop to simplify it in Ch4 int checksum = ((number.charAt(0) - '0' ) * 1 +(number.charAt(1) - '0' ) * 2 +(number.charAt(2) - '0' ) * 3 +(number.charAt(3) - '0' ) * 4 +(number.charAt(4) - '0' ) * 5 +(number.charAt(5) - '0' ) * 6 +(number.charAt(6) - '0' ) * 7 +(number.charAt(7) - '0' ) * 8 +(number.charAt(8) - '0' ) * 9) %11;System.out.print( "The ISBN-10 number is " + number);if (checksum == 10)System.out.println( "X" );elseSystem.out.println(checksum);}}4.20public class Exercise04_20 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter a string: " );String s = input.nextLine();System.out.println( "The length of the string is " + s.length());System.out.println( "The first character in the string is " +} }4.21public class Exercise04_21 {public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a SSN: ");String ssn = input.nextLine();boolean isValid = ssn.length() == 11 && Character.isDigit(ssn.charAt(0)) && Character.isDigit(ssn.charAt(1)) && Character.isDigit(ssn.charAt(2)) && ssn.charAt(3) =='-' && Character.isDigit(ssn.charAt(4)) &&Character.isDigit(ssn.charAt(5)) && ssn.charAt(6) =='-' Character.isDigit(ssn.charAt(7)) && Character.isDigit(ssn.charAt(8)) && Character.isDigit(ssn.charAt(9)) && Character.isDigit(ssn.charAt(10)); if (isValid)System.out.println(ssn + " is a valid social security number"elseSystem.out.println(ssn + " is an invalid social security number"} }4.22public class Exercise04_22 {public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter string s1: ");String s1 = input.nextLine(); System.out.print("Enter string s2: ");String s2 = input.nextLine();if (s1.indexOf(s2) != -1) {s.charAt(0));&&););System.out.println(s2 + " is a substring of " + s1); }else {System.out.println(s2 + " is not a substring of " + s1); }}}4.23public class Exercise04_23 {public static void main(String args[]) {Scanner input = new Scanner(System.in);// Obtain inputSystem.out.print( "Enter employee's name: " );String name = input.next();System.out.print( "Enter number of hours worked in a week: "); double hours = input.nextDouble();System.out.print( "Enter hourly pay rate: " );double payRate = input.nextDouble();System.out.print( "Enter federal tax withholding rate: " ); double fedTaxWithholdingRate = input.nextDouble();System.out.print( "Enter state tax withholding rate: " ); double stateTaxWithholdingRate = input.nextDouble();double grossPay = hours * payRate;double fedTaxWithholding = grossPay * fedTaxWithholdingRate;double stateTaxWithholding = grossPay * stateTaxWithholdingRate;double totalDeduction = fedTaxWithholding + stateTaxWithholding;double netPay = grossPay - totalDeduction;// Obtain output String out = "Employee Name: " + name + "\n\n" ;out += "Hours Worked:" + " " + hours + '\n' ;out += "Pay Rate:" + " $" + payRate + '\n' ;out += "Gross Pay:" + " $" + grossPay + '\n' ;out += "Deductions:\n" ;out += " Federal Withholding (" + fedTaxWithholdingRate *100'\n'+ "%):" + " $" + ( int )(fedTaxWithholding * 100) / 100.0 +out += " State Withholding (" + stateTaxWithholdingRate * 100 +"%):"+ " $" + ( int )(stateTaxWithholding * 100) / 100.0 + '\n'out += " Total Deduction:" + " $"+ ( int )(totalDeduction * 100) / 100.0 + '\n' ;out += "Net Pay:" + " $" + ( int )(netPay * 100) / 100.0;System.out.print(out);} }4.24public class Exercise04_24 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the first city: " );String s1 = input.nextLine();System.out.print( "Enter the second city: " );String s2 = input.nextLine();System.out.print( "Enter the third city: " );String s3 = input.nextLine();if (pareTo(s2) > 0) {// Swap s1 with s2String temp = s1;51= s2;52= temp;}if (pareTo(s3) > 0) {// Swap s2 with s3String temp = s2;52= s3;53= temp;}if (pareTo(s2) > 0) {// Swap s1 with s2String temp = s1;51= s2;52= temp;}System.out.print( "The three cities in alphabetical order are4.25public class Exercise04_25 {public static void main(String[] argds) {char ch1 = ( char )( 'A' + ( int )(Math.random() * 26));char ch2 = ( char )( 'A' + ( int )(Math.random() * 26));char ch3 = ( char )( 'A' + ( int )(Math.random() * 26));char ch4 = ( char )( '0' + ( int )(Math.random() * 10));char ch5 = ( char )( '0' + ( int )(Math.random() * 10));char ch6 = ( char )( '0' + ( int )(Math.random() * 10));char ch7 = ( char )( '0' + ( int )(Math.random() * 10));String vehiclePlateNumber = "" + ch1 + ch2 + ch3 + ch4 + ch5 + ch6 +ch7;+ s1 + + s2 + + s3);System.out.println( "A random vehicle plate number: "+ vehiclePlateNumber);}}4.26public class Exercise04_26 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print( "Enter the amount: " );String amountString = input.nextLine();int decimalPosition = amountString.indexOf( '.' );int amount; // amount in centsif (decimalPosition == -1) {amount = Integer.parseInt(amountString);}else {String fractionPart = amountString.substring(decimalPosition + 1);if (fractionPart.length() >= 2) {fractionPart = fractionPart.substring(0, 2);else if (fractionPart.length() == 1) {fractionPart = fractionPart + "0" ;}else {fractionPart = fractionPart + "00" ;}amount = Integer.parseInt(amountString.substring(0, decimalPosition) + fractionPart); }int remainingAmount = amount;// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount;// Display results"\t" + numberOfOneDollars + "\t" + numberOfQuarters + "\t" + numberOfDimes + "\t" + numberOfNickels + "\t" + numberOfPennies + System.out.print ln( "Your amount " + amountString + consists of \n" + dollars\n" +" quarters\n" +dimes\n" +" nickels\n" +" pennies" );。
Java语言程序设计(郑莉)第四章课后习题答案
Java语言程序设计第四章课后习题答案1.子类将继承父类所有的属性和方法吗?为什么?答:不,子类不能直接访问从父类中继承的私有属性及方法,但可以对公有及保护方法进行访问。
2.方法的覆盖与方法的重载有何不同?答:覆盖是运用在子类中实现与父类相同的功能,但采用不同的算法或公式;在名字相同的方法中,要做比父类更多的事情;在子类中需要取消从父类继承的方法。
3.声明两个带有无参构造方法的两个类A和B,声明A的子类C,并且声明B为C的一个成员,不声明C 的构造方法。
编写测试代码,生成类C的实例对象,并观察结果。
明一个基类A,它只有一种非默认构造方法;声明A的子类B,B 具有默认方法及非默认方法,并在B的构造方法中调用基类A的构造方法。
明一个类,它具有一种方法,此方法被重载三次,派生一个新类,并增加一种新的重载方法,编写测试类验证四种方法对于派生类验证四种方法对于派生类都有效。
明一个具有final方法的类,声明一个派生类,并试图对这个方法进行重写,会有什么结果。
明一个final类,并试图声明其派生类,会有什么结果。
么是抽象类?抽象类中是否一定要包括抽象方法?答:抽象类是一个不完全的类,不能使用new方法进行实例化。
抽象类可以包含抽象方法,也可以不包含抽象方法,但有抽象方法的必须是抽象类。
和super分别有哪些特殊含义?都有哪些种用法?答:this 表示当前类;super 表示调用父类。
在定义类的时候用到,this是当前对象的引用,super是当前对象的父类对象的引用,一般的都是把super用在构造函数中。
10.完成下面父类及子类的声明:(1) 声明Student类属性包括学号、姓名、英语成绩、数学成绩、计算机成绩和总成绩。
方法包括构造方法、get方法、set方法、toString方法、equals方法、compare方法(比较两个学生的总成绩,结果分为大于、小于、等于),sum方法(计算总成绩)和testScore方法(计算评测成绩)。
java第4章习题答案
2. 数 3. 4.
一个整型数组可以容纳的元素类型有哪些。 答:整型和字符型,byte 型 若有一个声明为“int[] a=new int[10]”的整型数组,可以引用的最小下标和 最大下标是多少? 答:最大下标为 0,最小下标为 9 若有一个声明为“int[] a=new int[10]”的整型数组,其每个元素的初始值是 多少? 答:初始值为 0 以下能对二维数组进行正确初始化的语句是( BC ) 。 A.int[][] a=new int[2][]{{1,2},{3,4}}; B. int[][] a=new int[][]{{1,2},{3,4}}; C. int[][ ] a={{1,2},{3,4}}; D. int[2][2] a={{1,2}下面程序的运行结果 class Happy { public static void main(String args[]) { int index=1; int a[] =new int[3]; int bas =a[index]; int baz =bas + index System.out.println( a[baz] ); } } 答:0
第四章 答案
1. 一个字符型数组,其有 5 个元素,初始值分别为'a','b','c','d','e',写出 可能的声明及初始化语句。 答 :(1)char[] ch={'a','b','c','d','e'}; (2) char[] ch=new char[5]; ch[0]='a'; ch[1]='b'; ch[2]='c'; ch[3]='d'; ch[4]='e'; (3) char[] ch=new char[]{'a','b','c','d','e'}; 获得一个数组可以容纳的元素个数的方法是什么? 答:利用数组型变量的一个整型属性 length,其表示数组可以容纳的元素个
解析java程序设计第四章课后答案
第4章习题解答1.类的继承的主要好处是什么?Java中支持类的多继承形式吗?继承是一种由已有的类创建新类的机制。
利用继承,我们可以先创建一个拥有共有属性的一般类,根据该一般类再创建具有特殊属性的新类,新类自动拥有一般类的属性和行为,并根据需要可以增加新的属性和行为,或者改变父类的行为。
类的继承的主要好处是代码复用。
Java不支持类的多继承形式。
2.解释一下方法重载和方法覆盖的概念,并对两者加以对比。
如果子类中定义方法所用的名称、返回类型和参数表和父类中方法所使用的完全一样,但具体实现不同,则称子类方法覆盖了父类中的方法。
在同一类中,如果方法名称相同,但参数表不同,则称为方法重载。
3.编写一个学生和教师的数据输入和显示程序。
学生数据有编号、姓名、班号和成绩,教师数据有编号、姓名、职称和部门。
要求将编号、姓名输入和显示设计成一个类Person,并作为学生类Student和教师类Teacher的父类。
import java.util.*;class Person{private String name;private int id;public void input(){Scanner sc=new Scanner(System.in);name=sc.nextLine();id=sc.nextInt();}public void display(){System.out.println("}}class Student extends Person{private int classNo;private int score;public void input(){super.input();Scanner sc=new Scanner(System.in);classNo=sc.nextInt();score=sc.nextInt();}public void display(){super.display();System.out.println("classNo="+classNo+" score="+score); }public static void main(String[] args){Student s=new Student();s.input();s.display();}}4.创建Animal(动物):Mouse,Dog等的一个继承分级结构。
《Java程序设计案例教程》第四章练习答案
第四章练习参考答案一、单项选择题1.对函数而言,下列叙述正确的是(D)。
A.一个程序中可以出现一个以上的主函数B.函数与主函数可以互相调用C.用户自定义的函数必须有形式参数D.调用函数和被调用函数可以不在同一个文件中2.在C++语言中,确定函数返回值的类型由(D)。
A.return语句中的表达式类型决定B.调用该函数的主函数类型决定C.调用该函数时系统状态决定D.定义函数时所指定的函数类型决定3.下列关于C++函数的叙述中,正确的是(C)。
A.每个函数至少要具有一个参数B.每个函数都必须返回一个值C.函数在被调用之前必须先声明D.函数不能自己调用自己4.函数调用语句calc(exp1,(exp2,exp3,exp4));中,含有的实参个数是(B)。
A.1B.2C.3D.45.调用函数时,若实参是一个数组名,则向函数对应的形参传送的是(B)。
A.数组元素的个数B.数组的首地址C.数组第一个元素的值D.数组中全部元素的值6.若已定义的函数有返回值,则以关于该函数调用的叙述中错误的是(D)。
A.调用可以作为独立的语句存在B.调用可以作为一个函数的实参C.调用可以出现在表达式中D.调用可以作为一个函数的形参7.有以下函数定义:void fun( int n,double x){…}若以下选项中的变量都已正确定义并赋值,则对函数fun()的正确调用语句是(C)。
A.fun(int y,double m);B.k=fun(10,12.5);C.fun(x,n);D.void fun(n,x);8.在C++语言中,函数的形式参数是(A)。
A.局部变量B.全局变量C.静态变量D.外部变量9.如果要一个变量在整个程序运行期间都存在,但是仅在说明它的函数内可见,则这个变量的存储类型应该被说明为(A)。
A.静态变量B.自动变量C.外部变量D.寄存器变量10.设有函数原型void test (int a,int b=7,char c="");,下面的函数调用中,属于不合法调用的是(C)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
4-1
class Y{
int a,b,y,i;
int sum=0;
public void f()
{
while(i>1){
y=b*(i-1)+a;
sum=sum+y;
i--;
}
System.out.println("等差数列的和为:"+sum);
}
}
public class XIN41{
public static void main(String args[]){
Y y1=new Y();
y1.sum=0;
java.util.Scanner sc =new java.util.Scanner(System.in); System.out.println("请输入首项的值a:");
y1.a =sc.nextInt();
System.out.println("请输入公差的值b:");
y1.b = sc.nextInt();
System.out.println("请输入项数i:"); y1.i = sc.nextInt();
y1.f();
}
}
4-2
class A
{
double a, b;
static double c;
double root1, root2;
boolean boo;
public A(double a, double b, double c) {
this.a = a;
this.b = b;
A.c = c;
if (a != 0)
{
boo = true;
else
{
boo = false;
}
}
public void getRoots()
{
if (boo)
{
System.out.println("是一元次方程");
double disk = b * b - 4 * a * c;
if (disk >= 0)
{
root1 = (-b + Math.sqrt(disk)) / (2 * a);
root2 = (-b - Math.sqrt(disk)) / (2 * a);
System.out.printf("方程的根:%f,%f\n", root1, root2); }
else
{
System.out.printf("方程没有实根\n");
}
else
{
System.out.println("不是一元次方程");
}
}
public void B(double a, double b, double c) {
this.a = a;
this.b = b;
A.c = c;
if (a != 0)
{
boo = true;
}
else
{
boo = false;
}
}
}
public class XIN42
public static void main(String args[ ]) {
A a1 = new A(4, 4, 1);
A a2 = new A(1, 2, 1);
a1.getRoots();
a2.getRoots();
}
}。