《Java语言程序设计:基础篇》课后复习题答案-第四章
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程序设计课后练习答案

《J a v a程序设计》课后练习答案第一章Java概述一、选择题1.( A )是在Dos命令提示符下编译Java程序的命令,( B )是运行Java程序的命令。
A.javacB.javaC.javadocD.javaw2.( D )不是Java程序中有效的注释符号。
A.//B.C.D.3.(A.B.C.D.4.JavaA.B.C.D.5.JavaA.1、JavaJava(JVM)Java以下图展示了Java程序从编译到最后运行的完整过程。
2、简述Java语言的特点Java具有以下特点:1)、简单性Java语言的语法规则和C语言非常相似,只有很少一部分不同于C语言,并且Java还舍弃了C语言中复杂的数据类型(如:指针和结构体),因此很容易入门和掌握。
2)、可靠性和安全性Java从源代码到最终运行经历了一次编译和一次解释,每次都有进行检查,比其它只进行一次编译检查的编程语言具有更高的可靠性和安全性。
3)、面向对象Java是一种完全面向的编程语言,因此它具有面向对象编程语言都拥有的封装、继承和多态三大特点。
4)、平台无关和解释执行Java语言的一个非常重要的特点就是平台无关性。
它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。
Java之所以能平台无关,主要是依靠Java虚拟机(JVM)来实现的。
Java编译器将Java源代码文件编译后生成字节码文件(一种与操作系统无关的二进制文件)5)、6)、Java来。
1、/****/}}第二章Java语法基础一、选择题1.下面哪个单词是Java语言的关键字( B )?A. DoubleB. thisC. stringD. bool2.下面属于Java关键字的是( D )。
A. NULLB. IFC. DoD. goto3.在启动Java应用程序时可以通过main( )方法一次性地传递多个参数。
如果传递的参数有多个,可以用空格将这些参数分割;如果某一个参数本身包含空格,可以使用( B )把整个参数引起来。
《Java基础入门》_课后习题答案大一计算机专业4

《Java基础入门》课后习题答案第4章面向对象(下)一、填空题1、一个类如果实现一个接口,那么它就需要实现接口中定义的全部方法,否则该类就必须定义成抽象类。
2、一个类可以从其他的类派生出来。
派生出来的类称为子类、用于派生的类称为父类或者基类。
3、定义一个Java 类时。
如果前面加使用final 关键词修饰,那么该类不可以被继承。
4、在Java语言中,所有的类都直接或间接继承自Object 类5、一个Lambda 表达式由三个部分组成,分别为参数列表、“->”、表达式主体二、判断题1、错2、对3、错4、对5、错1.抽象方法必须定义在抽象类中,所以抽象类中的方法都是抽象方法。
(×)2. Java 中被final 关键字修饰的变量,不能被重新赋值。
(√)3.不存在继承关系的情况下,也可以实现方法重写。
(×)4.函数式接口在Java中是指有且仅有一个抽象方法的接口。
(√)5.接口中只能定义常量和抽象方法。
(×)三、选择题1、B2、ABC3、C4、C5、A1.在类的继承关系中,需要遵循以下哪个继承原则?(B)A.多重B.单一C.双重D.不能继承2.关于super关键字以下说法哪些是正确的?(多选)(ABC)A. super 关键字可以调用父类的构造方法B.super 关键字可以调用父类的普通方法C. super 与this 不能同时存在于同一个构造方法中D. super 与this 可以同时存在于同一个构造方法中3.类中的一个成员方法被下面哪个修饰符修饰,该方法只能在本类被访问?(C)A. publicB. protectedC. privateD. default4.在Java中,要想让一个类继承另一个类,可以使用以下哪个关键字?(C)A. inheritsB. implementsC.extendsD. modifies5.已知类的继承关系如下:class Employee;class Manager extends Employeer class Director extends Employee;则以下语句能通过编译的有哪些?(A)A.Employee e=new Manager();B. Direetor d=new Manager();B.C. Director d=new Employee(); D. Manager menew Director();四、简答题1.简述什么是方法重写2.简述什么是多态。
《软件职业技术学院“十一五”规划教材: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章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基础第4章编程题答案

第四章编程题1. 按要求完成以下题目(1)Circle( ) // 将半径设为0Circle(double r ) // 创建 Circle 对象时将半径初始化为r③三个成员方法double getArea( ) //获取圆的面积double getPerimeter( ) // 获取圆的周长void show( ) //将圆的半径、周长、面积输出到屏幕(2)编写一个圆柱体类Cylinder ,它继承于上面的Circle 类。
还拥有:①一个成员变量double hight(私有,浮点型);// 圆柱体的高;②构造方法Cylinder (double r, double h )//创建Circle对象时将半径初始化为r③成员方法double getVolume( ) // 获取圆柱体的体积void showVolume( ) // 将圆柱体的体积输出到屏幕编写应用程序,创建类的对象,分别设置圆的半径、圆柱体的高,计算并分别显示圆半径、圆面积、圆周长,圆柱体的体积。
【参考答案】import java.math.*;class Circle{private double radius;public Circle() {radius=0;}public Circle(double r) {radius=r;}void setRadius(double r) {this.radius=r;}double getRadius(){return this.radius;}double getArea() {return Math.PI*radius*radius;}double getPerimeter() {return Math.PI*2*radius;}void show() {System.out.println("圆的半径为"+radius+"\n圆的周长为"+this.getPerimeter()+"\n圆的面积为"+this.getArea());}}class Cylinder extends Circle{double hight;public Cylinder(double r,double h) {super.setRadius(r);this.hight=h;}double getVolume(){double volume=super.getArea()*hight;return volume;}void showVolume() {System.out.println("圆柱的面积为"+this.getVolume());}}public class Example01 {public static void main(String[] args) {Circle circle=new Circle(5);circle.show();Cylinder cylinder=new Cylinder(2,5);cylinder.showVolume();}}2.按要求编写一个Java应用程序:(l)定义一个接口CanCry,描述会吼叫的方法public void cry()(2)分别定义狗类(Dog)和猫类(Cat),实现CanCry接口。
程序设计基础课后答案第四章

4.1 阅读下列程序,写出执行结果1.#include <iostream.h>void main(){ int i, conut=0, sum=0 ;float average ;int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } ;for( i=0; i<10; i++ ){ if( a[i] % 2 == 0 ) continue ;sum += a[ i ] ;conut ++ ;}average = sum / conut ;cout << "conut = " << conut << '\t' << "average = " << average << endl ;}2.#include <iostream.h>void main(){ int a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;int *p = a , sum = 0 ;for( ; p<a+9; p++ )if( *p % 2 == 0 ) sum += *p ;cout << "sum = " << sum << endl ;}3.const int n = 5 ;#include <iostream.h>#include <iomanip.h>void main(){ int a[n][n]={ 0 }, i, j, k ;for( k=1 , i=0 ; i<n ; i++ )for( j=i; j>= 0; j-- , k++ )a[j][i - j ] = k ;for( i=0 ; i<n ; i++ ){ for( j=0; j<n ; j++ )cout << setw( 3 ) << a[i][j] ;cout << endl ;}}4.int f(int [],int);#include <iostream.h>void main(){ int a[] = { -1, 3, 5, -7, 9, -11 } ;cout << f( a, 6 ) << endl ;}int f( int a[], int size ){ int i, t=1 ;for( i=0 ; i<size; i ++ )if( a[i]>0 ) t *= a[i] ;return t;}5.int f( int [][3], int, int ) ;#include <iostream.h>void main(){ int a[][3] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 } ;cout << f( a, 3, 3 ) << endl ;}int f( int a[][3], int row, int col ){ int i, j, t=1 ;for( i=0; i<row; i ++ )for( j=0; j<col; j++ ){ a[i][j] ++ ;if( i == j ) t *= a[i][j] ;}return t ;}6.#include<iostream.h>void test1( int *a1 ){ a1 = new int( 5 ) ;cout << "*a1 = " << *a1 << endl ;}void test2(int * & a2){ a2 = new int( 5 ) ;cout << "*a2 = " << *a2 << endl ;}void main(){ int *p = new int( 1 ) ;test1( p ) ;cout << "test1: *p1 = " << *p << endl ;test2( p ) ;cout << "test2: *p2 = " << *p << endl ;}7.#include <iostream.h>void main(){ char s[] = "abccda" ;int i ; char c ;for( i = 1 ; ( c=s[i] ) != '\0'; i ++ ){ switch( c ){ case 'a' : cout << '%' ; continue ;case 'b' : cout << '$' ; break ;case 'c' : cout << '*' ; break ;case 'd' : continue ;}cout << '#' << endl ;}}8.#include <iostream.h>void main(){ char *str[] = { "c++", "basic", "pascal" } ;char **p ;int i ;p = str ;for( i=0 ; i<3 ; i++ )cout << *( p+i ) << endl ;}9.#include <iostream.h>void main(){ char s1[] = "Fortran" , s2[] = "Foxpro" ;char *p , *q ;p = s1 ; q = s2 ;while( *p && *q ){ if ( *p == *q )cout << *p ;p ++ ;q ++ ;}cout << endl ;}10.#include <string.h>#include <iostream.h>void main(){ char str[][10] = { "vb", "pascal", "c++" }, s[10] ;strcpy( s , ( strcmp( str[0] , str[1] ) < 0 str[0] : str[1] ) ) ;if( strcmp( str[2], s ) < 0 ) strcpy( s, str[2] ) ;cout << s << endl ;}4.2 思考题1.数组说明语句要向编译器提供什么信息?写出一维数组、二维数组说明语句的形式。
Java语言程序设计 课后习题+答案

第一章课后习题1.编译Java程序的命令是什么?2.执行Java程序的命令是什么?3.Java应用程序和小程序的区别是什么?4.编写一个application ,实现在屏幕上打印自己名字的功能。
第一章课后习题答案1.编译Java程序的命令是什么?答案:javac 源文件名2.执行Java程序的命令是什么?java 主类名3.Java应用程序和小程序的区别是什么?Java application⏹由Java解释器独立运行字节码⏹由专门的命令行启动程序执行⏹程序中有定义了main()方法的主类Java applet⏹不能独立运行,字节码必须嵌入HTML文档⏹当浏览器调用含applet的Web页面时执行⏹程序中含有java. applet. Applet 类的子类4.编写一个application ,实现在屏幕上打印自己名字的功能。
class Test{public static void main(String[] args){System.out.println(“张三”);}}第二章课后习题(1)一、选择题1.下列变量定义错误的是。
A) int a; B) double b=4.5; C) boolean b=true; D)float f=9.8;2.下列数据类型的精度由高到低的顺序是:a)float,double,int,longb)double,float,int,bytec)byte,long,double,floatd)double,int,float,long3.执行完下列代码后,int a=3;char b='5';char c=(char)(a+b);c的值是?A)’8’ b)53 c)8 d)564.Unicode是一种_____________A) 数据类型 B)java包 C)字符编码 D)java类5.6+5%3+2的值是___________A)2 B)1 C) 9 D)106.下面的逻辑表达式中合法的是__________A)(7+8)&&(9-5) B)(9*5)||(9*7) C)9>6&&8<10 D)(9%4)&&(8*3) 7.java语言中,占用32位存储空间的是__________。
Java程序设计第1-4章练习题参考答案完整版

一、选择题1.下面供选字符序列中,不属于...Java语言关键字的是( A ) A.goto B.null C.false D.native2.以下是关于Java语言关键字的叙述,其中正确的是( C )A.关键字可以用来描述类的成员类型,但是不能描述普通变量B.关键字由字母(包括英文字母、下划线字符、美元字符、文字字符)和数字组成C.关键字不可以用作变量、方法、类或标号的标识符D.break和main都是Java语言的关键字3.下述字符组合不能作为Java程序标识符的是(D)A.Aa12 B.XC.y D.5x4.在下述字符串中,不属于...Java语言关键字的是( C )A.float B.newC.java D.return5.下列字符组合不能作为Java整型常量的是( A )A.078B.0x3ACBC.5000D.0x3ABC6.设有如下程序:public class Test {public static void main(String[] args) {String foo=args[1];String bar=args[2];String baz=args[3];System.out.println("baz= "+baz);}}下述哪一行命令可以使得执行该程序的输出为baz= 2 ( C )A) java Test 2222 B) java Test 1 2 3 4C) java Test 4 2 4 2 D) java Test 4 3 2 17.在Java语言中,int类型数据的长度是( C )A.1个字节B.2个字节C.4个字节D.8个字节8. 用Java虚拟机执行类名为Hello的应用程序的正确命令是( D )。
A) java Hello.class B) Hello.class C) java Hello.java D) java Hello9.执行以下代码,输出结果是( B )int x=5,y=7,u=9,v=6;System.out.println(x>y ? x+2:u>v ? u-3:v+2);A.8B.6C.7D.true10.下列修饰符中与访问控制无关的是(C)。
Java语言程序设计(郑莉)课后习题答案

1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
《Java语言程序设计-基础篇》答案-第04章

Q. 3
R. 3
4.19 答:(略)
4.20 答:输出:Sum is 15
4.21 答:第 1 个程序输出:5 4 3 2 1 第 2 个程序输出:1 2 3 4 5
4.22 答:(略)
4.23 答:源代码可以放在当前文件夹。 .class 文件应该存放在指定前文件夹的 java\chapter4 中。 使其它程序调用该类,配置 classpath 能找到该包所在文件夹。
4.24 答:ng 包的类可以不导入。
第 4 章 方法
复习题
4.1 答:(略)
4.2 答:void
4.3 答:方法如下: public static int max(int num1, int num2){ return num1 > num2 ? num1 : num2; }
4.4 答:不正确。
4.5 答:语法错误,“缺少返回语句”。 可以写 return。
4.18 答:结果如下: A. 2.0 B. -2.4492935982947064E-16 C. 1.0 D. 4.0 E. 1.0 F. 2.7182818284590455 G. 3 H. -2.0
I. -2.0 J. -3.0 K. -2 L. -2 M. 2.0 N. 3.0 O. 2.0 P. 3
4.6 答:不可以。
4.7 答:非 void void 非 void 非 void void 非 void 非 void
4.8 答:错误如下: 第 2 行:方法 method1 需要返回值类型,参数声明错误,应为 int n, int m。
4.9 答:(略)
4.10 答:值传递;可以同名。
4.11 答: (a)运行结果:0 (b)运行结果: Before the call, variable times is 3 n=3 Welcome to Java! n=2 Welcome to Java!
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程序设计 第四章 测验答案 慕课答案 UOOC优课 深圳大学继续教育学院

第4章测验-4.1继承概念一、单选题(共60.00分)1.下列关于继承的哪项叙述是正确的_______。
A.在java中允许多重继承B.在java中一个类只能实现一个接口C.在java中一个类不能同时继承一个类和实现一个接口D.java的单一继承使代码更可靠正确答案:D2.给出下面代码:1) class Parent {2) private String name;3) public Parent(){}4) }5) public class Child extends Parent {6) private String department;7) public Child() {}8) public String getValue(){ return name; }9) public static void main(String arg[]) {10) Parent p = new Parent();11) }12) }那些行将引起错误?A.第3行B.第6行C.第7行D.第8行正确答案:D3.设有下面两个类的定义:class Person {class Student extends Person{long id; // 身份证号int score; //入学总分String name; // 姓名int getScore() { return score; }}}问:类Person和类Student的关系是()。
A.包含关系B.继承关系(内部类继承了外部类)C.关联关系D.无关系,上述类定义有语法错误正确答案:B二、判断题(共40.00分)1.构造方法不能被继承。
A.正确B.错误正确答案:A2.一个子类可以重新定义从父类那里继承来的同名方法,而且允许它们有不同的返回值类型。
A.正确B.错误正确答案:B第4章测验-4.2成员变量/方法一、单选题(共33.20分)1.看下面一段程序:class Aclass{void go(){System.out.println(“Aclass“);}}public class Bclass extends Aclass{void go{System.out.println(“Bclass“);}public static void main(String args[]){Aclass a=new Aclass();Aclass a1=new Bclass();a.go();a1.go();}以上程序运行结果是:A.Aclass AclassB.Bclass BclassC.Aclass BclassD.Bclass Aclass正确答案:C2.在Java中,以下关于方法重载和方法重定义描述正确的是?A.方法重载和方法的重定义实现的功能相同B.方法重载出现在父子关系中,方法重定义是在同一类中C.方法重载的返回值类型必须一致,参数项必须不同D.方法重定义的返回值类型必须相同或相容。
【程序设计】java程序设计基础(第五版)第四章习题答案【精品资料】

1、将该学生的学习成绩按不同的分数段分为优、良、中、及格和不及格五个等级,从键盘上输入一个0~100之间的成绩,输出相应的等级,要求用switch语句实现。
import java.util.*;public class student {public static void main(String[] args) {Scanner reader=new Scanner(System.in);int i;System.out.println("please input 0~100:");i=reader.nextInt();switch(i/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("不及格");break;}}}2、设学生的学习成绩按如下的分数段评定为四个等级:85~100为A,70~84为B,60~69为C,0~59为D。
从键盘上输入一个0~100之间的成绩,要求用switch语句根据成绩,评定并输出相应的等级。
import java.util.*;public class student {public static void main(String[] args) {Scanner reader=new Scanner(System.in);int i;System.out.println("please input 0~100:");i=reader.nextInt();switch(i/5){ case 17: System.out.println("A");break;case 18: System.out.println("A");break;case 19: System.out.println("A");break;case 20: System.out.println("A");break;}switch(i/5){ case 14: System.out.println("B");break;case 15: System.out.println("B");break;case 16: System.out.println("B");break;}switch(i/5){ case 12: System.out.println("C");break;case 13: System.out.println("C");break;}switch(i/30){case 0: System.out.println("D");break;case 1: System.out.println("D");break;}}}3、编写一个java应用程序,输出由1~100之间所有既有可以被3整除,又可以被7整除的数。
解析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等的一个继承分级结构。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
System.out.println("The sum is " + sum); } }
class TestContinue { public static void main(String[] args) { int sum = 0; int number = 0;
15. The keyword break is used to exit the current loop. The program in (A) will terminate. The output is Balance is 1.
The keyword continue causes the rest of the loop body to be skipped for the current iteration. The while loop will not terminate in (B).
2147483647 + 1 is actually -2147483648
25. (A)
n times
(B) n+1 times
(C) n-5 times
(D) The ceiling of (n-5)/3 times
16. Yes.
for (int i=1; sum < 10000; i++) sum = sum + i;
17. If a continue statement is executed inside a for loop, the rest of the iteration is skipped, then the action-after-each-iteration is performed and the loop-continuationcondition is checked. If a continue statement is executed inside a while loop, the rest of the iteration is skipped, then the loop-continuation-condition is checked.
1 2 1 2 2 3
20. After the continue statement is executed, the statement
j++
will be executed. The output of this fragment is
1 2 1 2 2 3
21. Line 2: missing static. Line 3: The semicolon (;) at the end of the for loop heading should be removed. Line 4: sum not defined. Line 6: the semicolon (;) at the end of the if statement should be removed. Line 6: j not defined. Line 7: Missing a semicolon for the first println statement. Line 11: The semicolon (;) at the end of the while heading should be removed. Line 18: Missing a semicolon at the end of the do-while loop.
6. The three parts in a for loop control are as follows:
The first part initializes the control variable. The second part is a Boolean expression that determines whether the loop will repeat. The third part is the adjustment statement, which adjusts the control variable.
while (number < 20) { number++; if (number != 10 && number != 11) sum += number;
}
System.out.println("The sum is " + sum); } }
19. After the break statement is executed, the last println statement is executed. The output of this fragment is
for (int i=1; i<=100; i++) System.out.println(i)m is 14 count is 5
9.
max is 5 number 0
10. The loop keeps doing something indefinitely.
ij 10 11 20
output 0
0
21
1
22
30
0
31
1
32
2
33
40
0
41
1
42
2
43
3
44
(A). 0010120123
(B). **** **** 2 **** 3 2 **** 4 3 2 ****
(C). 1xxx2xxx4xxx8xxx16xxx 1xxx2xxx4xxx8xxx 1xxx2xxx4xxx 1xxx2xxx 1xxx
Chapter 4 Loops
1. count < 100 always true at Point A. count < 100 always false at Point C. count < 100 is sometimes true or sometimes false at Point B.
(D). 1G 1G3G 1G3G5G 1G3G5G7G 1G3G5G7G9G
24.
x is -2147483648
The reason:
When a variable is assigned a value that is too large (in size) to be stored, it causes overflow.
22. (A) compile error: i is not initialized.
(B) Line 3: The ; at the end of for loop should be removed.
for (int i = 0; i < 10; i++);
23.
Tip for tracing programs: Draw a table to see how variables change in the program. Consider (a) for example.
int sum = 0; int number; do {
number = input.nextInt(); sum += number; } while (number != 0);
5. Same. When the i++ and ++i are used in isolation, their effects are same.
Here is the fix:
int i = 0;
while (i < 4) { if (i % 3 == 0) { i++; continue; } sum += i; i++;
}
18. class TestBreak { public static void main(string[]args) { int sum = 0; int number = 0;
2.
It would be wrong if it is initialized to a value between 0 and 100, because it could be the number you attempt to guess.
3. (a) Infinite number of times. (b) Infinite number of times. (c) The loop body is executed nine times. The printout is 3, 5, 7, 9 on
separate lines.
4. The difference between a do-while loop and a while loop is the order of evaluating the continuation-condition and executing the loop body. In a while loop, the continuation-condition is checked and then, if true, the loop body is executed. In a do-while loop, the loop body is executed for the first time before the continuationcondition is evaluated.
13. while loop: long sum = 0; int i=0; while (i<=1000) { sum += i++; }