JAVA实验7-9+参考答案

合集下载

java语言程序设计方案课后习题答案

java语言程序设计方案课后习题答案

习题23.使用“= =”对相同内容的字符串进行比较,看会产生什么样的结果。

答:首先创建一个字符串变量有两种方式:String str = new String("abc")。

String str = "abc";使用“= =”会因为创建的形式不同而产生不同的结果:String str1 = "abc"。

String str2 = "abc"。

System.out.println(str1==str2)。

//trueString str1 = new String("abc")。

String str2 = "abc"。

System.out.println(str1==str2)。

//falseString str1 = new String("abc")。

String str2 = new String("abc")。

System.out.println(str1==str2)。

//false因此自符串如果是对内容进行比较,使用equals方法比较可靠。

String str1 = "abc"。

String str2 = "abc"。

System.out.println(str1==str2)。

//trueString str1 = new String("abc")。

String str2 = "abc"。

System.out.println(str1.equals(str2))。

//trueString str1 = new String("abc")。

String str2 = new String("abc")。

Java语言程序设计(郑莉)第九章课后习题答案要点

Java语言程序设计(郑莉)第九章课后习题答案要点

Java语言程序设计第九章课后习题答案1.编写一个程序,该程序绘制一个5×9的网络,使用drawLine方法。

//NetWork类import java.awt.Graphics;import javax.swing.JFrame;public class NetWork extends JFrame{public NetWork(){// 设置窗体大小this.setSize(130, 130);//设置窗体大小不可改变this.setResizable(false);// 设置默认关闭方式,关闭窗体的同时结束程序this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 将窗体显示出来this.setVisible(true);}//横纵格之间都间隔10像素,起点在(20,40)public void paint(Graphics g){//绘制横向线for(int i=0;i<=5;i++){g.drawLine(20, 40+i*10, 110, 40+i*10);}//绘制纵向线for(int i=0;i<=9;i++){g.drawLine(20+i*10, 40, 20+i*10, 90);}}}//test9_1类public class test9_1 {public static void main(String[] args){new NetWork();}}运行结果:2.编写一个程序,该程序以不同的颜色随机产生三角形,每个三角形用不同的颜色进行填充。

//Triangle类import java.awt.Color;import java.awt.Graphics;import java.util.Random;import javax.swing.JFrame;public class Triangle extends JFrame{Random rnd = new Random();//这里定义4个三角形int[][] x=new int[4][3];int[][] y=new int[4][3];int[][] color=new int[4][3];public Triangle(){for(int i=0;i<4;i++){for(int j=0;j<3;j++){color[i][j]=rnd.nextInt(255);x[i][j]=rnd.nextInt(i*100+100);y[i][j]=rnd.nextInt(i*100+100)+50;//加50像素是为了避免顶到窗体上沿}}//窗体标题this.setTitle("随机三角形");//窗体大小this.setSize(500,500);//窗体大小不可变this.setResizable(false);//关闭窗体的同时结束程序this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//显示窗体this.setVisible(true);}public void paint(Graphics g){for(int i=0;i<4;i++){g.setColor(new Color(color[i][0],color[i][1],color[i][2]));g.fillPolygon(x[i], y[i], 3);}}}//test9_2public class test9_2 {public static void main(String[] args){new Triangle();}}运行结果:3.编写一个Applet,该程序请求用户输入圆的半径,然后显示该圆的直径、周长和面积。

JAVA程序设计课后习题及答案7

JAVA程序设计课后习题及答案7

第7章1.Swing是一个用于开发Java应用程序界面的工具包,它以抽象窗口工具包(abstract window toolkit,AWT)为基础,使跨平台应用程序可以使用任何可插拔的外观风格。

只用很少的代码就可以利用Swing丰富、灵活的功能和模块化组件来创建优雅的用户界面。

也可以这样说,Swing是Java平台的UI(user interface),充当了处理用户与计算机之间全部交互的角色。

相对于AWT来说,Swing的主要优势就在于MVC体系结构的普遍使用。

因为为了简化组件的设计工作,在Swing组件中,视图和控件两部分被合为一体。

每个组件都有一个相关的分离模型和它使用的界面(包括视图和控件)。

2.Swing组件从功能上可以按下面的类型来划分。

(1)顶层容器:如JFrame、JApplet、JDialog、JWindow。

(2)中间容器:如JPanel、JScrollPane、JSplitPane、JToolBar。

(3)特殊容器:在GUI上起特殊作用的中间层,如JInternalFrame、JLayeredPane、JRootPane。

(4)基本控件:实现人机交互的组件,如JButton、JComboBox、JList、JMenu、JSlider、JTextField。

(5)不可编辑信息的显示:向用户显示不可编辑信息的组件,如JLabel、JProgressBar、ToolTip。

(6)可编辑信息的显示:向用户显示可被编辑的格式化信息的组件,如JColorChooser、JFileChooser、JTable、JTextArea。

3.(1)面板(JPanel)。

面板是一个轻量级容器组件,用于容纳界面元素,以便在布局管理器的设置下容纳更多的组件,实现容器的嵌套。

JPanel、JScrollPane、JSplitPane和JInternalFrame都属于常用的中间容器,都是轻量级组件。

JPanel的默认布局管理器是FlowLayout。

java习题及答案第9章 习题参考答案

java习题及答案第9章 习题参考答案

第9章习题解答1.与输入/输出有关的流类有哪些?答:与输入/输出有关的流类主要有InputStream、OutputStream和Reader、Writer类及其子类。

除此以外,与流有关的类还有File类、FileDescriptor类、StreamTokenizer类和RandomAccessFile类。

2.字节流与字符流之间有哪些区别?答:字节流是面向字节的流,流中的数据以8位字节为单位进行读写,是抽象类InputStream和OutputStream的子类,通常用于读写二进制数据,如图像和声音。

字符流是面向字符的流,流中的数据以16位字符(Unicode字符)为单位进行读写,是抽象类Reader和Writer的子类,通常用于字符数据的处理。

3.什么是节点流?什么是处理流或过滤流?分别在什么场合使用?答:一个流有两个端点。

一个端点是程序;另一个端点可以是特定的外部设备(如键盘、显示器、已连接的网络等)和磁盘文件,甚至是一块内存区域(统称为节点),也可以是一个已存在流的目的端。

流的一端是程序,另一端是节点的流,称为节点流。

节点流是一种最基本的流。

以其它已经存在的流作为一个端点的流,称为处理流。

处理流又称过滤流,是对已存在的节点流或其它处理流的进一步处理。

对节点流中的数据只能按字节或字符读写。

当读写的数据不是单个字节或字符,而是一个数据块或字符串等时,就要使用处理流或过滤流。

4.标准流对象有哪些?它们是哪个类的对象?答:标准流对象有3个,它们是:System.in、System.out和System.err。

System.in 是InputStream类对象,System.out和System.err是PrintStream类对象。

5.顺序读写与随机读写的特点分别是什么?答:所谓顺序读写是指在读写流中的数据时只能按顺序进行。

换言之,在读取流中的第n个字节或字符时,必须已经读取了流中的前n-1个字节或字符;同样,在写入了流中n-1个字节或字符后,才能写入第n个字节或字符。

java实验答案全.doc

java实验答案全.doc
}
public void Display(){
if(this.average>=80) status = 1;
else statu$=O;
if(status==l) System.out.println(name+":通过!");if(status==O) System.out.println(name+••:不通过!’•);
}
public float get_y(){ return this.y;
}
//显示点的位罝
public String getLocation(){
String str = "("+(this.x)+","+(this.y)+")"+"\n"; return str;
}
//修改点的坐标
public void changeLocation(float a,float b){
st2.Display();
}
}
实验
2.按照要求编写Java Application程序。
假定要为某个公司编写雇员工资支付程序。这个公司有各种类型的雇员(Employee),不同类型的雇员按不同的方式支付工资:
经理(Manager):每月获得一份固定的工资;
销售人员(Salesman):在基本工资的基础上每月还有销售提成;
class Student {
public String name; public double a,b,c; public double average; int status;
}
class Undergraduate extends Student {

Java语言程序设计(郑莉)第七章课后习题答案

Java语言程序设计(郑莉)第七章课后习题答案

Java语言程序设计第七章课后习题答案1.数组的声明与数组元素的创建有什么关系?答:声明数组仅仅是代表试图创建数组,不分配任何存储空间,声明是为创建做“铺垫”。

2.Vector类的对象与数组有什么关系?什么时候适合使用数组,什么时候适合使用Vector?答:vector是一个能够存放任意对象类型的动态数组,容量能自动扩充,而数组存储固定且类型相同的对象;对于存储固定类型相同的对象使用数组,对于存储不同类型或者动态调整数组大小的情况使用Vector。

3.与顺序查找相比,二分查找有什么优势?使用二分查找的条件?答:对于大数据量中进行查找时二分查找比顺序查找效率高得多;条件是已排序的数组。

4.试举出三种常见的排序算法,并简单说明其排序思路。

答:①选择排序:基本思想是站在未排序列中选一个最小元素,作为已排序子序列,然后再重复地从未排序子序列中选取一个最小元素,把它加到已经排序的序列中,作为已排序子序列的最后一个元素,直到把未排序列中的元素处理完为止。

②插入排序:是将待排序的数据按一定的规则逐一插入到已排序序列中的合适位置处,直到将全部数据都插入为止。

③二分查找:将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。

重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

5.声明一个类People,成员变量有姓名、出生日期、性别、身高、体重等;生成10个People 类对象,并放在一个以为数组中,编写方法按身高进行排序。

//People类public class People{private String name;private String birthdaydate;private String sex;private double height;private double weight;public People(){//默认构造函数}public People(People p){=;this.birthdaydate=p.birthdaydate;this.sex=p.sex;this.height=p.height;this.weight=p.weight;}public People(String name,String birthdaydate,String sex,double height,double weight){=name;this.birthdaydate=birthdaydate;this.sex=sex;this.height=height;this.weight=weight;}public String getName() {return name;}public void setName(String name) { = name;}public String getBirthdaydate() {return birthdaydate;}public void setBirthdaydate(String birthdaydate) {this.birthdaydate = birthdaydate;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public String toString(){return"姓名:"+name+"\n出生年月:"+birthdaydate+"\n性别:"+sex+"\n 身高:"+height+"\n体重:"+weight;}}//test7_5类public class test7_5 {/***@param args*/public static void main(String[] args) {// TODO Auto-generated method stubPeople[] people={new People("林楚金","1989年8月13日","男",182,63.5),new People("诸葛亮","181年7月23日","男",184,76.6),new People("迈克杰克逊","1958年8月29日","男",180,60),new People("乔丹","1963年2月17日","男",198,98.1),new People("拿破仑","1769年8月15日","男",159.5,63),new People("苍井空","1983年11月11日","女",155,45),};People temp=new People();for(int i=0;i<people.length-1;i++)for(int j=i+1;j<people.length;j++){if(people[i].getHeight()<people[j].getHeight()){temp=people[j];people[j]=people[i];people[i]=temp;}}System.out.println("按身高从小到大排序后的结果如下:");for(int i=0;i<people.length;i++)System.out.println(people[i]+"\n");}}运行结果:6.声明一个类,此类使用私有的ArrayList来存储对象。

Java语言程序设计课后习题答案全集

Java语言程序设计课后习题答案全集

Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。

为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。

一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。

在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。

- 多行注释:使用"/* */" 可以在多行中添加注释。

- 文档注释:使用"/** */" 可以添加方法或类的文档注释。

2. 什么是Java的数据类型?请列举常见的数据类型。

答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。

- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。

二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。

答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。

JAVA实验7-9+答案

JAVA实验7-9+答案

试验【2 】71. 编一个程序,包含以下文件.(1)Shape.java文件,在该文件中界说接口Shape,该接口在shape包中.属性:PI.办法:求面积的办法area().(2)Circle.java文件,在该文件中界说圆类Circle,该类在circle包中,实现Shape接口.属性:圆半径radius.办法:结构办法;实现接口中求面积办法area();求周长办法perimeter().(3)“Cylinder.java”文件,在该文件中界说圆柱体类Cylinder,该类口在cylinder包中,持续圆类.属性:圆柱体高度height.办法:结构办法;求表面积办法area();求体积办法volume().(4)X5_3_6.java文件,在该文件中界说主类X5_3_6,该类在默认包中,个中包含主办法main(),在主办法中创建两个圆类对象cir1和cir2,具体尺寸本身肯定,并显示圆的面积和周长;再创建两个圆柱体类的对象cy1和cy2,具体尺寸本身肯定,然后分别显示圆柱体cy1和cy2的底圆的面积和周长以及它们各自的体积和表面积. 【编程剖析】本题重要考核接口.包.持续.封装等问题.编程步骤如下:第一步:起首创建p1包,在个中创建Shape接口// Shape.java文件package p1;// 创建p1包public interface Shape{// 界说Shape接口…}第二步:创建Circle类和Cylinder类,它们都界说在p2包中.// Circle.java文件package p2;// 创建p2包import p1.*;public class Circle implements Shape{// 界说实现Shape接口的Circle类…}// Cylinder.java文件package p2;public class Cylinder extends Circle{// 创建持续Circle类的Cylinder类…}第三步:创建主类,在个中的main()办法中创建对象,实现响应的功效.// X5_3_6.java文件package p3;import p2.*;public class X5_3_6 { // 界说主类public static void main(String[] args) {…}}【参考程序】// X5_3_6.java文件package p3;import p2.*;public class X5_3_6 { // 界说主类public static void main(String[] args) {Circle cir1 = new Circle(120.5);Circle cir2 = new Circle(183.8);System.out.println("cir1.area: "+cir1.area());System.out.println("cir1.perimeter: "+cir1.perimeter());System.out.println("cir2.area: "+cir2.area());System.out.println("cir2.perimeter: "+cir2.perimeter());Cylinder cy1 = new Cylinder(27.3,32.7);Cylinder cy2 = new Cylinder(133.5,155.8);System.out.println("cy1.area: "+cy1.area());System.out.println("cy1.volume: "+cy1.volume());System.out.println("cy2.area: "+cy2.area());System.out.println("cy2.volume: "+cy2.volume());}}// Shape.java文件package p1;// 创建p1包public interface Shape{// 界说Shape接口double PI=Math.PI;double area();// 求面积办法}// Circle.java文件package p2;// 创建p2包import p1.*;public class Circle implements Shape{// 界说实现Shape接口的Circle类double radius;// 半径public Circle(double r){radius = r;}public double area(){// 实现Shape接口中的办法(这是必须的)return PI*radius*radius;}public double perimeter(){// 界说求圆周长的办法return 2*PI*radius;}}// Cylinder.java文件package p2;public class Cylinder extends Circle{// 创建持续Circle类的Cylinder类double height;public Cylinder(double r,double h){super(r);height = h;}public double area(){return 2*PI*radius*radius+2*PI*radius*height;}public double volume(){return PI*radius*radius*height;}}2)界说一个接口OneToN,在接口中包含一个抽象办法disp().界说Sum和Pro类,并分别用不同代码实现ONeToN的disp()办法,在Sum的办法中盘算1~n的和,在Pro的办法中盘算1~n的乘积interface OneToN{public void disp(int n);}class Sum implements OneToN{public void disp(int n){int sum=0;for(int i=1;i<=n;i++){sum=sum+i;}System.out.println(sum);}}class Pro implements OneToN{public void disp(int n){long pro=1;for(int i=1;i<=n;i++){pro=pro*i;}System.out.println(pro);}}public class interfaceTest {public static void main(String[] args) { // TODO code application logic here Sum x=new Sum();x.disp(100);}}3)改错,上传准确答案,并以注释情势给出错误原因class SuperClass{public SuperClass(String msg){ System.out.println("SuperClass constructor: " +msg);}}class SubClass extends SuperClass{public SubClass(String msg){Super(msg); //父类没有无参的结构办法,应采用super显示挪用父类的结构办法System.out.println("SubClass constructor");}}public class Test1 {public static void main(String[] args) {SubClass descendent = new SubClass();}}4)应用多态性编程,创建一个抽象类shape类,界说一个函数Area为求面积的公共办法,再界说Triangle,Rectangle和circle类,实现computerArea办法;增长display办法,显示name和area,并在Triangle,Rectangle和circle类笼罩该办法,并为每个类增长本身的结构办法;在主类中创建不同对象,求得不同外形的面积.答案略.试验8一.选择题1.关于平常的寄义,下列描写中最准确的一个是( D ).A.程序编译错误B.程序语法错误C.程序自界说的平常事宜D.程序编译或运行时产生的平常事宜【解析】平常就是程序编译或运行时产生的平常事宜.2.自界说平常时,可以经由过程对下列哪一项进行持续?( C )A.Error类B.Applet类C.Exception类及其子类D.AssertionError类【解析】自界说平常类时,该类必须持续Exception类及其子类.3.对应try和catch子句的分列方法,下列哪一项是准确的?( A )A.子类平常在前,父类平常在后B.父类平常在前,子类平常在后C.只能有子类平常 D.父类和子类不能同时出如今try语句块中【解析】对应try和catch子句的分列方法,请求子类平常(规模小的平常)在前,父类平常(规模大的平常)在后.4.运行下面程序时,会产生什么平常?( A )public class X7_1_4 {public static void main(String[] args) {int x = 0;int y = 5/x;int[] z = {1,2,3,4};int p = z[4];}}A.ArithmeticExceptionB.NumberFormatExceptionC.ArrayIndexOutOfBoundsException D.IOException【解析】当程序履行到“int y = 5/x”语句时,产生平常,程序中断履行,是以产生ArithmeticException平常. 5.运行下面程序时,会产生什么平常?( C )public class X7_1_5 {public static void main(String[] args) {int[] z = {1,2,3,4};int p = z[4];int x = 0;int y = 5/x;}}A.ArithmeticExceptionB.NumberFormatExceptionC.ArrayIndexOutOfBoundsException D.IOException【解析】当程序履行到“int p = z[4]”语句时,产生平常,程序中断履行,是以产生ArrayIndexOutOfBoundsException平常.6.下列程序履行的成果是( B ).public class X7_1_6 {public static void main(String[] args) {try{return;}finally{System.out.println("Finally");}}}A.程序正常运行,但不输出任何成果B.程序正常运行,并输出FinallyC.编译经由过程,但运行时消失平常D.因为没有catch子句,是以不能经由过程编译【解析】在履行try-catch-finally语句块时,最后必须履行finally语句块中的内容,而本程序没有平常产生,是以程序正常运行,并输出Finally.7.下列代码中给出准确的在办法体内抛出平常的是( B ).A.new throw Exception("");B.throw new Exception("");C.throws IOException();D.throws IOException;【解析】在办法体内抛出平常时只能应用throw,而不能应用throws,别的,“new Exception("")”是创建一个平常,是以B是准确的.8.下列描写了Java说话经由过程面相对象的办法进行平常处理的利益,请选出不在这些利益规模之内的一项( C )A.把各类不同的平常事宜进行分类,表现了优越的持续性B.把错误处理代码从常规代码平分别出来C.可以应用平常处理机制代替传统的掌握流程D.这种机制对具有动态运行特征的庞杂程序供给了强有力的支撑【解析】平常处理机制不能代替传统的流程掌握.二.编程题1.编写一个体系主动抛出的.体系自行处理的数组大小为负数的程序.【编程剖析】当编写的程序中没有处理平常的语句时,体系会主动抛出平常,并自行进行处理.【参考程序】public class X7_3_1 {public static void main(String[] args){int[] a = new int[-5];for(int i=0; i<a.length; i++){a[i] = 10 + i;}}}【运行成果】Exception in thread "main" ng.NegativeArraySizeExceptionat X7_3_1.main(X7_3_1.java:3)2.编写一个由throw抛出的.体系自行处理的数组下标越界的程序.【编程剖析】当由throw抛出平常后,假如程序本身不进行平常处理,Java体系将采用默认的处理方法进行处理.【参考程序】import java.io.*;public class X7_3_2 {public static void main(String[] args)throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);int[] a = new int[5];int n = Integer.parseInt(br.readLine());if(n>5) // 当输入的n值大于5时将由throw抛出平常throw new ArrayIndexOutOfBoundsException();System.out.println("程序持续履行");for(int i=0; i<n; i++){a[i] = 10 + i;System.out.print(a[i]+"\t");}System.out.println();}}【运行成果】8Exception in thread "main" ng.ArrayIndexOutOfBoundsExceptionat C1.main(C1.java:9)3.编写一个体系主动抛出的.由try-catch捕捉处理的分母为0以及数组下标越界的程序.【编程剖析】当在try语句块中消失分母为0的情形时,假如在catch参数中有ArithmeticException对象,则就能捕捉到该平常并进行处理;同样,当在try语句块中消失分母为数组下标越界的情形时,假如在catch参数中有ArrayIndexOutOfBoundsException对象,则就能捕捉到该平常并进行处理.【参考程序】import java.io.*;public class X7_3_3 {public static void main(String args[]) throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);System.out.println("请输入两个整数:");int a = Integer.parseInt( br.readLine());int b = Integer.parseInt( br.readLine());try{// 当输入的b为0时,就会消失算术平常System.out.println(a/b);}catch(ArithmeticException e){// 捕捉算术平常并进行处理System.out.println("消失被0除的情形!");}int c[] =new int[4], sum = 0;try{// 当消失数组下标越界时就会抛出平常for(int i = 0; i<5; i++) sum += c[i];System.out.println( " sum = " + sum);}catch(ArrayIndexOutOfBoundsException e){// 捕捉数组下标越界平常并处理System.out.println("数组下标越界!");}}}【运行成果】请输入两个整数:20消失被0除的情形!数组下标越界!4.编写一个由throw抛出的.由try-catch捕捉处理的分母为0以及数组下标越界的程序.【编程剖析】当在程序消失平常之前应用throw语句来抛出平常,可以做到防患于未然,提进步行平常处理,将由被动处理平常改变为主动防止平常产生.【参考程序】import java.io.*;public class X7_3_4 {public static void main(String args[]) throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);System.out.println("请输入两个整数:");int a = Integer.parseInt( br.readLine());int b = Integer.parseInt( br.readLine());try{if(b==0)throw new ArithmeticException("抛出算术平常");System.out.println(a/b);}catch(ArithmeticException e){e.printStackTrace();System.out.println("消失被0除的情形!");}int c[] ={1, 2, 3, 4}, sum = 0;try{for(int i = 0; i<5; i++) {if(i >= 4)throw new ArrayIndexOutOfBoundsException("抛出数组下标越界平常");sum += c[i];System.out.println( " sum = " + sum);}}catch(ArrayIndexOutOfBoundsException e){e.printStackTrace();System.out.println("数组下标越界!");}}}5.自界说两个平常类NumberTooBigException和NumberTooSmallException,在个中界说各自的结构办法,分别打印输出“产生数字太大平常”和“产生数字太小平常”.然后在主类中界说一个带throws的办法numberException(int x),当x>100时经由过程throw抛出NumberTooBigException平常,当x<0时经由过程throw抛出NumberTooSmallException平常;最后在main()办法中挪用该办法,实现从键盘中输入一个整数,假如输入的是负数,激发NumberTooSmallException平常,假如输入的数大于100,激发.NumberTooBigException平常,不然输出“没有产生平常”.【编程剖析】本题重要考核自界说平常的办法.第一步:界说平常类NumberTooBigExceptionclass NumberTooBigException extends Exception{NumberTooBigException(){super("产生数字太大平常 ");}}第二步:界说平常类NumberTooSmallExceptionclass NumberTooSmallException extends Exception{NumberTooSmallException(){super("产生数字太小平常");}}第三步:在主类X7_3_5中界说numberException()办法.public static void numberException(int x)throws NumberTooBigException, NumberTooSmallException{if(x>100)throw new NumberTooBigException();else if (x<0)throw new NumberTooSmallException();elseSystem.out.println("没有平常产生");}第四步:在main()办法中挪用numberException()办法并捕捉和处来由此办法引起的平常.【参考程序】import java.io.*;public class X7_3_5 {public static void main(String args[]) throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);System.out.print("请输入一个整数:");int a = Integer.parseInt( br.readLine());try{numberException(a);}catch(NumberTooBigException e){e.printStackTrace();}catch(NumberTooSmallException e){e.printStackTrace();}}public static void numberException(int x) throws NumberTooBigException, NumberTooSmallException{ if(x>100)throw new NumberTooBigException();else if (x<0)throw new NumberTooSmallException();elseSystem.out.println("没有平常产生");}}class NumberTooBigException extends Exception{NumberTooBigException(){super("产生数字太大平常 ");}}class NumberTooSmallException extends Exception{NumberTooSmallException(){super("产生数字太小平常");}}试验9一.选择题1.下列说法中错误的一项是( B ).A.构件是一个可视化的能与用户在屏幕上交互的对象B.构件可以或许自力显示出来C.构件必须放在某个容器中才能准确显示D.一个按钮可所以一个构件【解析】构件不能自力显示,它必须放在某个容器中才能准确显示.2.进行Java根本GUI设计须要用到的包是( C ).A.java.ioB.java.sqlC.java.awtD.java.rmi【解析】进行Java根本GUI设计须要用到的包是java.awt和javax.swing 3.Container是下列哪一个类的子类( D )?A.GraphicsB.WindowC.AppletD.Component【解析】Container类是由Component类派生的.4.java.awt.Frame的父类是( B ).A.java.util.WindowB.java.awt WindowC.java.awt PanelD.java.awt.ScrollPane【解析】java.awt.Frame的父类java.awt Window.5.下列哪个办法可以将MenuBar参加Frame中( D )?A.setMenu()B.addMenuBar()C.add()D.setMenuBar()【解析】可以将MenuBar参加Frame中的办法是setMenuBar().6.下列论述中,错误的一项是( D ).A.采用GridLayout布局,容器中的每个构件平均分派容器空间B.采用GridLayout布局,容器中的每个构件形成一个收集状的布局C.采用GridLayout布局,容器中的构件按照从左到右.从上到下的次序分列D.采用GridLayout布局,容器大小改变时,每个构件不再平均分派容器空间【解析】采用GridLayout布局,容器大小改变时,每个构件平均分派容器空间. 7.当单击鼠标或拖动鼠标时,触发的事宜是( D ).A.KeyEventB.ActionEventC.ItemEventD.MouseEvent【解析】对鼠标操作,触发的事宜是MouseEvent事宜.8.下列哪一项不属于Swing的顶层组件( C )?A.JAppletB.JDialogC.JTreeD.Jframe【解析】JTree只有在容器中才能显示,它不属于swing的顶层组件.9.下列说法中错误的一项是( D ).A.在现实编程中,一般应用的是Component类的子类B.在现实编程中,一般应用的是Container类的子类C.Container类是Component类的子类D.容器中可以放置构件,但是不可以或许放置容器【解析】容器中既可以放置构件,也可以放置容器.10.下列哪一项不属于AWT布局治理器( D )?A.GridLayoutB.CardLayoutC.BorderLayoutD.BoxLayout【解析】BoxLayout属于swing布局治理器,不属于AWT布局治理器.11.下列说法中错误的一项是( A ).A.MouseAdapter是鼠标活动适配器 B.WindowAdapter是窗口适配器C.ContainerAdapter是容器适配器D.KeyAdapter是键盘适配器【解析】MouseAdapter是鼠标适配器,而MouseMotionAdapte才是鼠标活动适配器.12.布局治理器可以治理构件的哪个属性( A )?A.大小B.色彩C.名称D.字体【解析】布局治理器可以治理构件的地位和大小,而不能治理构件的其他属性.13.编写AWT图形用户界面的时刻,必定要import的语句是( B ).A.import java.awt; B.import java.awt.*;C.import javax.awtD.import javax.swing.*;【解析】“import java.awt.*;”语句的寄义是加载awt包中的所有类,而其他都不是.14.在类中若要处理ActionEvent事宜,则该类须要实现的接口是( B ).A.RunnableB.ActionListenerC.SerializableD.Event【解析】处理ActionEvent事宜的类须要实现的接口是ActionListener,它个中包含了actionPerformed()办法. 15.下列不属于java.awt包中的根本概念的一项是( C ).A.容器B.构件C.线程D.布局治理器【解析】线程不属于java.awt包中的根本概念的一项,其他三个都是.16.下列关于AWT构件的说法中错误的一项是( D ).A.Frame是顶级窗口,它无法直接监听键盘输入事宜B.对话框须要依附于其他窗口而消失C.菜单只能被添加到菜单栏中D.可以将菜单添加到随意率性容器的某处【解析】菜单只能添加到Applet.Frame等容器中,不能添加到随意率性容器的某处.17.JPanel的默认布局治理器是( C ).A.BorderLayoutB.GridLayoutC.FlowLayoutD.CardLayout【解析】Panel.JPanel和Applet的默认布局治理器都是FlowLayout.18.下列说法中错误的是( B ).A.在Windows体系下,Frame窗口是有标题.边框的B.Frame的对象实例化后,没有大小,但是可以看到C.经由过程挪用Frame的setSize()办法来设定窗口的大小D.经由过程挪用Frame的setVisible(true)办法来设置窗口为可见【解析】Frame的对象实例化后,没有大小,也不能看到,只有经由过程挪用Frame的setSize()和setVisible(true)办法才能设定窗口的大小和可见性.19.下列说法中错误的是( D ).A.统一个对象可以监听一个事宜源上多个不同的事宜B.一个类可以实现多个监听器接口C.一个类中可以同时消失事宜源和事宜处理者D.一个类只能实现一个监听器接口【解析】一个类可以实现多个监听器接口,从而实现对多个事宜的监听.20.下列选项中不属于容器的一项是().A.WindowB.PanelC.FlowLayoutD.ScrollPane【解析】FlowLayout类属于布局治理器,而不属于容器.二.编程题1.创建一个Frame类型窗口,在窗口中添加2个不同色彩的Panel面板,每个面板中添加2个按钮构件.【编程剖析】本程序重要考核窗口.面板以及按钮的创建及布局问题.第一步:起首界说一个主类,让该类持续Frame类.第二步:界说该类的数据成员,包括两个Panel对象,一个长度为4的Button对象数组.第三步:创建类的工作办法,在办法中创建各个对象.设置对象属性.布局全部界面.设置窗口大小并显示界面.第四步:在类的main()办法中创建本类对象,从而显示全部窗口界面.【参考程序】import java.io.*;import java.awt.*;public class X10_3_1 extends Frame{Panel pn1,pn2;// 界说面板Button[] bt = new Button[4]; // 界说按钮数组public static void main(String[] args)throws IOException{new X10_3_1 ();}public X10_3_1 (){pn1 = new Panel();// 创建面板对象pn2 = new Panel();pn1.setBackground(Color.yellow);// 设置面板背景色彩pn2.setBackground(Color.green);for(int i=0; i<4; i++){// 创建按钮对象bt[i] = new Button("Button"+(i+1));}pn1.add(bt[0]);// 向面板中添加按钮,面板的默认布局为FlowLayoutpn1.add(bt[1]);pn2.add(bt[2]);pn2.add(bt[3]);add(pn1,BorderLayout.NORTH);// 向窗口添加面板,窗口默认布局为BorderLayout add(pn2,BorderLayout.SOUTH);。

java第七版课后答案——第二章

java第七版课后答案——第二章

//******************************************************************** // AverageOfThree.java Author: Lewis/Loftus//// Solution to Programming Project 2.2//******************************************************************** import java.util.Scanner;public class AverageOfThree{//----------------------------------------------------------------- // Reads three integers from the user and prints their average.//----------------------------------------------------------------- public static void main <String[] args>{int num1, num2, num3;double average;Scanner scan = new Scanner <System.in>;System.out.print <"Enter the first number: ">;num1 = scan.nextInt<>;System.out.print <"Enter the second number: ">;num2 = scan.nextInt<>;System.out.print <"Enter the third number: ">;num3 = scan.nextInt<>;average = <double> <num1+num2+num3> / 3;System.out.println <"The average is: " + average>;}}//******************************************************************** // AverageOfThree2.java Author: Lewis/Loftus//// Alternate solution to Programming Project 2.2//******************************************************************** import java.util.Scanner;public class AverageOfThree2{//----------------------------------------------------------------- // Reads three integers from the user and prints their average.//----------------------------------------------------------------- public static void main <String[] args>{int num1, num2, num3;double average;Scanner scan = new Scanner <System.in>;System.out.print <"Enter three numbers: ">;num1 = scan.nextInt<>;num2 = scan.nextInt<>;num3 = scan.nextInt<>;average = <double> <num1+num2+num3> / 3;System.out.println <"The average is: " + average>;}}//******************************************************************** // Balloons.java Author: Lewis/Loftus//// Solution to Programming Project 2.17//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class Balloons extends JApplet{//----------------------------------------------------------------- // Draws a set of balloons on strings.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.white>;// draw the stringspage.setColor <Color.black>;page.drawLine <45, 95, 100, 300>;page.drawLine <90, 100, 100, 300>;page.drawLine <60, 100, 100, 300>;page.drawLine <122, 85, 100, 300>;page.drawLine <145, 115, 100, 300>;// draw the balloonspage.setColor <Color.blue>;page.fillOval <20, 30, 50, 65>;page.setColor <Color.yellow>;page.fillOval <70, 40, 40, 60>;page.setColor <Color.red>;page.fillOval <40, 50, 40, 55>;page.setColor <Color.green>;page.fillOval <100, 30, 45, 55>;page.setColor <Color.cyan>;page.fillOval <120, 55, 50, 60>;}}//******************************************************************** // BigDipper.java Author: Lewis/Loftus//// Solution to Programming Project 2.16//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class BigDipper extends JApplet{//----------------------------------------------------------------- // Draws the Big Dipper constellation and some other stars.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.black>;page.setColor <Color.white>;page.drawLine <100, 80, 110, 120>;page.drawLine <110, 120, 165, 115>;page.drawLine <165, 115, 175, 70>;page.drawLine <100, 80, 175, 70>;page.drawLine <175, 70, 245, 20>;page.drawLine <245, 20, 280, 30>;// Draw some extra starspage.fillOval <50, 50, 4, 4>;page.fillOval <70, 150, 3, 3>;page.fillOval <90, 30, 3, 3>;page.fillOval <220, 140, 4, 4>;page.fillOval <280, 170, 3, 3>;page.fillOval <310, 100, 4, 4>;page.fillOval <360, 20, 3, 3>;}}//******************************************************************** // BusinessCard.java Author: Lewis/Loftus//// Solution to Programming Project 2.20//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class BusinessCard extends JApplet{//----------------------------------------------------------------- // Draws a business card.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.yellow>;page.setColor <Color.red>;page.fillOval <10, 20, 60, 60>;page.setColor <Color.cyan>;page.fillRect <25, 35, 130, 25>;page.setColor <Color.black>;page.drawString <"James C. Kerplunk", 35, 50>;page.drawString <"President and CEO", 85, 80>;page.drawString <"Origin Software, Inc.", 85, 100>;page.drawLine <225, 20, 225, 80>;page.drawLine <195, 50, 255, 50>;page.setColor <Color.blue>;page.drawString <"where it all begins...", 115, 135>;}}//******************************************************************** // ChangeCounter.java Author: Lewis/Loftus//// Solution to Programming Project 2.10//******************************************************************** import java.util.Scanner;public class ChangeCounter{//----------------------------------------------------------------- // Computes the total value of a collection of coins.//----------------------------------------------------------------- public static void main <String[] args>{int quarters, dimes, nickels, pennies;int total, dollars, cents;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the number of quarters: ">;quarters = scan.nextInt<>;System.out.print <"Enter the number of dimes: ">;dimes = scan.nextInt<>;System.out.print <"Enter the number of nickels: ">;nickels = scan.nextInt<>;System.out.print <"Enter the number of pennies: ">;pennies = scan.nextInt<>;total = quarters * 25 + dimes * 10 + nickels * 5 + pennies;dollars = total / 100;cents = total % 100;System.out.println <"Total value: " + dollars + " dollars and " + cents + " cents.">;}//******************************************************************** // DrawName.java Author: Lewis/Loftus//// Solution to Programming Project 2.15//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class DrawName extends JApplet{//----------------------------------------------------------------- // Draws a name.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.cyan>;page.setColor <Color.black>;page.drawString <"John A. Lewis", 50, 50>;}}//******************************************************************** // FloatCalculations.java Author: Lewis/Loftus//// Solution to Programming Project 2.4//******************************************************************** import java.util.Scanner;public class FloatCalculations{//----------------------------------------------------------------- // Reads two floating point numbers and prints their sum,// difference, and product.//----------------------------------------------------------------- public static void main <String[] args>{float num1, num2;Scanner scan = new Scanner <System.in>;System.out.print <"Enter the first number: ">;num1 = scan.nextFloat<>;System.out.print <"Enter the second number: ">;num2 = scan.nextFloat<>;System.out.println <"Their sum is: " + <num1+num2>>;System.out.println <"Their difference is: " + <num1-num2>>;System.out.println <"Their product is: " + <num1*num2>>;}//******************************************************************** // Fraction.java Author: Lewis/Loftus//// Solution to Programming Project 2.13//******************************************************************** import java.util.Scanner;public class Fraction{//----------------------------------------------------------------- // Computes the floating point equivalent of a fraction.//----------------------------------------------------------------- public static void main <String[] args>{int numerator, denominator;float value;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the numerator: ">;numerator = scan.nextInt<>;System.out.print <"Enter the denominator: ">;denominator = scan.nextInt<>;value = <float> numerator / denominator;System.out.println <"Floating point equivalent: " + value>;}}//******************************************************************** // HousePicture.java Author: Lewis/Loftus//// Solution to Programming Project 2.19//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class HousePicture extends JApplet{//----------------------------------------------------------------- // Draws a house scene.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.cyan>;page.setColor <Color.gray>;page.fillRect <0, 200, 400, 50>; // groundpage.setColor <Color.blue>;page.fillRect <50, 125, 300, 100>; // housepage.setColor <Color.green>;page.fillRect <180, 175, 40, 50>; // doorpage.setColor <Color.yellow>;page.fillRect <100, 155, 40, 25>; // windowpage.fillRect <260, 155, 40, 25>; // windowpage.setColor <Color.black>;page.fillRect <40, 100, 320, 40>; // roofpage.fillOval <210, 200, 6, 6>; // doorknobpage.setColor <Color.red>;page.fillRect <80, 80, 20, 40>; // chimneypage.setColor <Color.darkGray>;page.fillOval <80, 60, 20, 20>; // smokepage.fillOval <85, 50, 15, 25>; // smokepage.fillOval <90, 45, 15, 20>; // smokepage.setColor <Color.white>;page.fillOval <200, 30, 80, 40>; // cloudpage.fillOval <230, 40, 80, 40>; // cloud}}//******************************************************************** // InfoParagraph.java Author: Lewis/Loftus//// Solution to Programming Project 2.3//******************************************************************** import java.util.Scanner;public class InfoParagraph{//----------------------------------------------------------------- // Reads information about a person and incorporates it into an// output paragraph.//----------------------------------------------------------------- public static void main <String[] args>{String name, age, college, pet;Scanner scan = new Scanner <System.in>;System.out.print <"What is your name? ">;name = scan.nextLine<>;System.out.print <"How old are you? ">;age = scan.nextLine<>;System.out.print <"What college do you attend? ">;college = scan.nextLine<>;System.out.print <"What is your pet's name? ">;pet = scan.nextLine<>;System.out.println <>;System.out.print <"Hello, my name is " + name + " and I am ">;System.out.print <age + " years\nold. I'm enjoying my time at ">; System.out.print <college + ", though\nI miss my pet " + pet>;System.out.println <" very much!">;System.out.println <>;}}//******************************************************************** // Lincoln4.java Author: Lewis/Loftus//// Solution to Programming Project 2.1//******************************************************************** public class Lincoln4{//----------------------------------------------------------------- // Prints a quote from Abraham Lincoln, including quotation// marks.//----------------------------------------------------------------- public static void main <String[] args>{System.out.println <"A quote by Abraham Lincoln:">;System.out.println <"\"Whatever you are, be a good one.\"">;}}//******************************************************************** // MilesToKilometers.java Author: Lewis/Loftus//// Solution to Programming Project 2.6//******************************************************************** import java.util.Scanner;public class MilesToKilometers{//----------------------------------------------------------------- // Converts miles into kilometers. The value for miles is read// from the user.//----------------------------------------------------------------- public static void main <String[] args>{final double MILES_PER_KILOMETER = 1.60935;double miles, kilometers;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the distance in miles: ">;miles = scan.nextDouble<>;kilometers = MILES_PER_KILOMETER * miles;System.out.println <"That distance in kilometers is: " +kilometers>;}}//******************************************************************** // MoneyConversion.java Author: Lewis/Loftus//// Solution to Programming Project 2.11//******************************************************************** import java.util.Scanner;public class MoneyConversion{//----------------------------------------------------------------- // Reads a monetary amount and computes the equivalent in bills// and coins.//----------------------------------------------------------------- public static void main <String[] args>{double total;int tens, fives, ones, quarters, dimes, nickels;int remainingCents;Scanner scan = new Scanner<System.in>;System.out.print <"Enter monetary amount: ">;total = scan.nextDouble<>;remainingCents = <int> <total * 100>;tens = remainingCents / 1000;remainingCents %= 1000;fives = remainingCents / 500;remainingCents %= 500;ones = remainingCents / 100;remainingCents %= 100;quarters = remainingCents / 25;remainingCents %= 25;dimes = remainingCents / 10;remainingCents %= 10;nickels = remainingCents / 5;remainingCents %= 5;System.out.println <"That's equivalent to:">;System.out.println <tens + " ten dollar bills">;System.out.println <fives + " five dollar bills">;System.out.println <ones + " one dollar bills">;System.out.println <quarters + " quarters">;System.out.println <dimes + " dimes">;System.out.println <nickels + " nickels">;System.out.println <remainingCents + " pennies">;}}//******************************************************************** // OlympicRings.java Author: Lewis/Loftus//// Solution to Programming Project 2.18//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class OlympicRings extends JApplet{//----------------------------------------------------------------- // Draws the olympic logo.//----------------------------------------------------------------- public void paint <Graphics page>{final int DIAMETER = 50;setBackground <Color.lightGray>;page.setColor <Color.blue>;page.drawOval <30, 40, DIAMETER, DIAMETER>;page.setColor <Color.yellow>;page.drawOval <60, 70, DIAMETER, DIAMETER>;page.setColor <Color.black>;page.drawOval <90, 40, DIAMETER, DIAMETER>;page.setColor <Color.green>;page.drawOval <120, 70, DIAMETER, DIAMETER>;page.setColor <Color.red>;page.drawOval <150, 40, DIAMETER, DIAMETER>;}}//******************************************************************** // PieChart.java Author: Lewis/Loftus//// Solution to Programming Project 2.22//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class PieChart extends JApplet{//----------------------------------------------------------------- // Draws the pie chart with equal sections.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.lightGray>;page.setColor <Color.blue>;page.fillArc <70, 25, 100, 100, 0, 45>;page.setColor <Color.yellow>;page.fillArc <70, 25, 100, 100, 45, 45>;page.setColor <Color.black>;page.fillArc <70, 25, 100, 100, 90, 45>;page.setColor <Color.green>;page.fillArc <70, 25, 100, 100, 135, 45>;page.setColor <Color.red>;page.fillArc <70, 25, 100, 100, 180, 45>;page.setColor <Color.magenta>;page.fillArc <70, 25, 100, 100, 225, 45>;page.setColor <Color.cyan>;page.fillArc <70, 25, 100, 100, 270, 45>;page.setColor <Color.orange>;page.fillArc <70, 25, 100, 100, 315, 45>;}}//******************************************************************** // Seconds.java Author: Lewis/Loftus//// Solution to Programming Project 2.8//******************************************************************** import java.util.Scanner;public class Seconds{//----------------------------------------------------------------- // Computes the total number of seconds for a given number of// hours, minutes, and seconds.//----------------------------------------------------------------- public static void main <String[] args>{final int SECONDS_PER_HOUR = 3600;final int SECONDS_PER_MINUTE = 60;int seconds, minutes, hours, totalSeconds;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the number of hours: ">;hours = scan.nextInt<>;System.out.print <"Enter the number of minutes: ">;minutes = scan.nextInt<>;System.out.print <"Enter the number of seconds: ">;seconds = scan.nextInt<>;totalSeconds = hours * SECONDS_PER_HOUR +minutes * SECONDS_PER_MINUTE +seconds;System.out.println <>;System.out.println <"Total seconds: " + totalSeconds>;}}//******************************************************************** // Seconds2.java Author: Lewis/Loftus//// Solution to Programming Project 2.9//******************************************************************** import java.util.Scanner;public class Seconds2{//----------------------------------------------------------------- // Computes the number of hours, minutes, and seconds that are// equivalent to the number of seconds entered by the user.//----------------------------------------------------------------- public static void main <String[] args>{final int SECONDS_PER_HOUR = 3600;final int SECONDS_PER_MINUTE = 60;int seconds, minutes, hours;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the number of seconds: ">;seconds = scan.nextInt<>;hours = seconds / SECONDS_PER_HOUR;seconds = seconds % SECONDS_PER_HOUR; // remaining secondsminutes = seconds / SECONDS_PER_MINUTE;seconds = seconds % SECONDS_PER_MINUTE; // remaining secondsSystem.out.println <>;System.out.println <"Hours: " + hours>;System.out.println <"Minutes: " + minutes>;System.out.println <"Seconds: " + seconds>;}}//******************************************************************** // ShadowName.java Author: Lewis/Loftus//// Solution to Programming Project 2.21//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class ShadowName extends JApplet{//----------------------------------------------------------------- // Draws a name with a slightly offset shadow.//----------------------------------------------------------------- public void paint <Graphics page>{setBackground <Color.yellow>;page.setColor <Color.black>;page.drawString <"John A. Lewis", 50, 50>;page.setColor <Color.red>;page.drawString <"John A. Lewis", 49, 49>;}}//******************************************************************** // Snowman2.java Author: Lewis/Loftus//// Solution to Programming Project 2.14//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class Snowman2 extends JApplet{//----------------------------------------------------------------- // Draws a snowman with added features.//----------------------------------------------------------------- public void paint <Graphics page>{final int MID = 130;final int TOP = 50;setBackground <Color.cyan>;page.setColor <Color.blue>;page.fillRect <0, 175, 300, 50>; // groundpage.setColor <Color.yellow>;page.fillOval <260, -40, 80, 80>; // sunpage.setColor <Color.white>;page.fillOval <MID-20, TOP, 40, 40>; // headpage.fillOval <MID-35, TOP+35, 70, 50>; // upper torsopage.fillOval <MID-50, TOP+80, 100, 60>; // lower torsopage.setColor <Color.red>;page.fillOval <MID-3, TOP+50, 6, 6>; // buttonpage.fillOval <MID-3, TOP+60, 6, 6>; // buttonpage.setColor <Color.black>;page.fillOval <MID-10, TOP+10, 5, 5>; // left eyepage.fillOval <MID+5, TOP+10, 5, 5>; // right eyepage.drawArc <MID-10, TOP+20, 20, 10, 10, 160>; // frownpage.drawLine <MID-25, TOP+60, MID-50, TOP+40>; // left armpage.drawLine <MID+25, TOP+60, MID+55, TOP+60>; // right armpage.drawLine <MID-20, TOP+5, MID+20, TOP+5>; // brim of hatpage.fillRect <MID-15, TOP-20, 30, 25>; // top of hatpage.drawString <"John Lewis", 20, 20>; // artist}}//******************************************************************** // SquareCalculations.java Author: Lewis/Loftus//// Solution to Programming Project 2.12//******************************************************************** import java.util.Scanner;public class SquareCalculations{//----------------------------------------------------------------- // Computes a square's perimeter and area given the length of// one side.//----------------------------------------------------------------- public static void main <String[] args>{int side, perimeter, area;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the length of a square's side: ">;side = scan.nextInt<>;perimeter = side * 4;area = side * side;System.out.println <"Perimeter: " + perimeter>;System.out.println <"Area: " + area>;}}//******************************************************************** // TempConverter2.java Author: Lewis/Loftus//// Solution to Programming Project 2.5//******************************************************************** import java.util.Scanner;public class TempConverter2{//----------------------------------------------------------------- // Computes the Celsius equivalent of a Fahrenheit value read// from the user. Uses the formula C = <5/9><F - 32>.//----------------------------------------------------------------- public static void main <String[] args>{final int BASE = 32;final double CONVERSION_FACTOR = 5.0 / 9.0;double celsiusTemp, fahrenheitTemp;Scanner scan = new Scanner<System.in>;System.out.print <"Enter a Fahrenheit temperature: ">;fahrenheitTemp = scan.nextDouble<>;celsiusTemp = CONVERSION_FACTOR * <fahrenheitTemp - BASE>;System.out.println <"Celsius Equivalent: " + celsiusTemp>;}}//******************************************************************** // TravelTime.java Author: Lewis/Loftus//// Solution to Programming Project 2.7//******************************************************************** import java.util.Scanner;public class TravelTime{//----------------------------------------------------------------- // Converts miles into kilometers. The value for miles is read// from the user.//----------------------------------------------------------------- public static void main <String[] args>{int speed, distance;double time;Scanner scan = new Scanner<System.in>;System.out.print <"Enter the speed: ">;speed = scan.nextInt<>;System.out.print <"Enter the distance traveled: ">;distance = scan.nextInt<>;time = <double> distance / speed;System.out.println <"Time elapsed during trip: " + time>;}}。

java习题附答案

java习题附答案

java习题附答案Java习题附答案在学习Java编程语言的过程中,练习习题是非常重要的一部分。

通过解决习题,我们可以更好地理解和掌握Java的语法和特性。

下面将给大家提供一些Java习题,并附上答案,希望能帮助大家更好地学习和掌握Java编程。

1. 编写一个Java程序,输出1到100之间所有的偶数。

```javapublic class EvenNumbers {public static void main(String[] args) {for (int i = 1; i <= 100; i++) {if (i % 2 == 0) {System.out.println(i);}}}}```2. 编写一个Java程序,计算1到100之间所有奇数的和。

```javapublic class SumOfOddNumbers {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i++) {if (i % 2 != 0) {sum += i;}}System.out.println("Sum of odd numbers from 1 to 100: " + sum); }}```3. 编写一个Java程序,判断一个数是否为素数。

```javapublic class PrimeNumber {public static void main(String[] args) {int num = 29;boolean isPrime = true;for (int i = 2; i <= num / 2; i++) {if (num % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(num + " is a prime number.");} else {System.out.println(num + " is not a prime number.");}}}```通过以上习题的练习,我们可以更好地理解Java的循环、条件判断等基本语法,也能够提高我们的编程能力和解决问题的能力。

java习题集及答案

java习题集及答案

java习题集及答案《Java习题集及答案》Java作为一种广泛应用于软件开发领域的编程语言,对于初学者来说,掌握其基本语法和常见的编程技巧是非常重要的。

为了帮助初学者更好地掌握Java编程,我们整理了一些常见的习题集及其答案,希望能够对大家的学习有所帮助。

1. 编写一个Java程序,实现将两个整数相加并输出结果的功能。

```javapublic class AddTwoNumbers {public static void main(String[] args) {int num1 = 5;int num2 = 10;int sum = num1 + num2;System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);}}```2. 编写一个Java程序,实现将一个字符串反转并输出结果的功能。

```javapublic class ReverseString {public static void main(String[] args) {String str = "Hello, World!";StringBuilder reversed = new StringBuilder();reversed.append(str);reversed = reversed.reverse();System.out.println("The reversed string is: " + reversed.toString());}}```3. 编写一个Java程序,实现计算一个整数的阶乘并输出结果的功能。

```javapublic class Factorial {public static void main(String[] args) {int num = 5;int factorial = 1;for (int i = 1; i <= num; i++) {factorial *= i;}System.out.println("The factorial of " + num + " is " + factorial);}}```通过以上的习题集及答案,我们可以看到一些常见的Java编程问题的解决方法。

Java实验

Java实验

实验一熟悉Java开发环境(验证性2学时)一、实验目的与要求:1 掌握Java Application程序的开发过程并编写第一个Java Application程序*2 掌握Java Applet程序的开发过程并编写第一个Java Applet程序。

*3 练习简单的HTML文件配合Java Applet使用。

4 熟悉jdk的使用二、实验内容:1 编写一个Java Application程序,在屏幕上显示”This is my first java program!”.*2 编写第一个Java Applet 程序,在屏幕上显示”This is my first Java Applet!”三、实验步骤:1、jdk的使用jdk开发工具包可以从网站下载,jdk不是集成编译环境,须手动运用命令行程序进行编译和解释执行1)编辑.java文件可以在记事本或其他纯文本编辑器中编辑,保存时把文件扩展名定为.java即可,当然要注意文件名命名的要求2)编译生成.class文件进入dos系统进行编译(如图1.1所示),格式如javac MyFirstApplication.java,要注意图1.1进入命令行看javac.exe的路径并且MyFirstApplication.java文件路径和javac.exe路径一样。

编译成功后就能在浏览器中看见多了一个MyFirsApplication.class或更多的.class文件。

如图1.2所示图1.2使用jdk编译MyFirstApplication.java文件3)解释执行Application程序:同样是在dos系统下解释执行,格式如java MyFirstApplication,注意.class后缀别加,如图1.3所示。

图1.3解释执行MyFirstApplication.class程序* applet程序进入dos系统进行编译,格式如javac MyFirstApplet.java,要注意看javac.exe的路径并且MyFirstApplet.java文件路径和javac.exe路径一样。

PTA7-9作业总结

PTA7-9作业总结

PTA7-9作业总结PTA第7~9次作业总结7-1: 图形卡⽚排序游戏本题主要运⽤集合ArrayList,接⼝,继承相关的知识;ArrayList主要⽅法有①添加元素add()⽅法;:add(object value) ;将指定元素object value追加到集合的末尾; add(int index, Object obj);功能:在集合中指定index位置,添加新元素obj②删除元素:remove()③获取数组长度:size()④替换元素:set(a,b):⑤清空集合内所有元素clear()⑥查找元素get(int index);返回指定元素本题还运⽤到⼀个知识点:运⽤了接⼝Collection.sort排序⽅法接⼝:抽象⽅法只能存在于抽象类或者接⼝中,但抽象类中却能存在⾮抽象⽅法,即有⽅法体的⽅法.接⼝是百分之百的抽象类我们不能直接取实例化⼀个接⼝,因为接⼝中的⽅法都是抽象的,没有⽅法体的,那如何产⽣具体的实例呢?我们可以使⽤接⼝类型的引⽤指向⼀个实现了该接⼝的对象,并且调⽤这个接⼝中的⽅法.⼀个类可以实现多个接⼝,⼀个接⼝可以继承于另外⼀个接⼝,⼀个类如果要实现某个接⼝的话,那么它必须要实现这个接⼝的所有⽅法.接⼝中所有的⽅法都是抽象的和public .接⼝的实现主要是⽤来弥补⽆法实现多继承的局限多态的理解: 多态是继封装、继承之后,⾯向对象的第三⼤特性。

多态现实意义理解:现实事物经常会体现出多种形态,如学⽣,学⽣是⼈的⼀种,则⼀个具体的同学张三既是学⽣也是⼈,即出现两种形态。

Java作为⾯向对象的语⾔,同样可以描述⼀个事物的多种形态。

如Student类继承了Person类,⼀个Student的对象便既是Student,⼜是Person。

3.多态体现为⽗类引⽤变量可以指向⼦类对象。

4.前提条件:必须有⼦⽗类关系。

5.多态中成员的特定:多态成员变量:编译运⾏看左边Fu f=new Zi();System.out.println(f.num);//f是Fu中的值,只能取到⽗中的值多态成员⽅法:编译看左边,运⾏看右边Fu f1=new Zi();System.out.println(f1.show());//f1的门⾯类型是Fu,但实际类型是Zi,所以调⽤的是重写后的⽅法。

java习题7答案与解析

java习题7答案与解析

java习题7答案与解析Java习题7答案与解析Java是一门广泛应用于软件开发领域的编程语言,具有简洁、可移植、高效等特点。

在学习Java的过程中,习题是不可或缺的一部分,通过解答习题可以提高编程能力和理解对Java的掌握程度。

本文将为大家提供一些Java习题7的答案与解析,希望对大家的学习有所帮助。

1. 请编写一个Java程序,实现将一个字符串中的大写字母转换为小写字母,并输出结果。

答案与解析:可以使用String类的toLowerCase()方法将字符串中的大写字母转换为小写字母。

具体代码如下:```javapublic class ConvertToUpper {public static void main(String[] args) {String str = "Hello World";String result = str.toLowerCase();System.out.println(result);}}```2. 请编写一个Java程序,实现计算一个数组中所有元素的和,并输出结果。

答案与解析:可以使用循环遍历数组,将每个元素累加到一个变量中,最后输出结果。

具体代码如下:public class ArraySum {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};int sum = 0;for (int i = 0; i < arr.length; i++) {sum += arr[i];}System.out.println("数组元素的和为:" + sum);}}```3. 请编写一个Java程序,实现将一个字符串按照指定分隔符分割,并输出结果。

答案与解析:可以使用String类的split()方法将字符串按照指定分隔符进行分割,并将结果存储在一个字符串数组中。

Java程序设计基础与实战-习题答案(人邮) 第9章作业参考答案

Java程序设计基础与实战-习题答案(人邮) 第9章作业参考答案

第9章作业参考答案1.填空题Component MenuComponent(1)WindowListenerFlowLayout(2)AWT(5)事件事件源事件监听器2.选择简答题(1)回答要点•awt是基于本地方法的C/C++程序,其运行速度比拟快;而swing是基于awt的Java程序,其运行速度比拟慢。

•AWT的控件在不同的平台可能表现不同,而Swing在所有平台表现一致。

•AWT和Swing的实现原理不同。

•AWT的图形函数与操作系统提供的图形函数有着一一对应的关系;而Swing不仅提供了AWT的所有功能,还用纯粹的Java代码对AWT的功能进行了大幅度的扩充。

•awt是抽象窗口组件工具包,是java最早的用于编写图形节目应用程序的开发包(2)回答要点在java.awt包中提供了5中常用的布局管理器,分别式FlowLayouK流式布局管理器)、BorderLayout (边界布局管理器)、GridLayout (网格布局管理器)、GridBagLayout(网格包布局管理器)和CradLayout (卡片布局管理器)(3)回答要点事件处理机制专门用于响应用户的操作,比方,想要响应用户的点击鼠标、按下键盘等操作,就需耍使用AWT的事件处理机制。

AWT事件处理机制中几个比拟重要的概念如下所示:•事件对象(Event):封装了GUI组件上发生的特定事件(通常就是用户的一次操作)事件源(组件):事件发生的场所,通常就是产生事件的组件。

•监听器(Listener):负责监听事件源上发生的事件,并对各种事件做出响应处理的对象(对象中包含事件处理器)。

•事件处理器:监听器对象对接收的事件对象进行相应处理的方法。

(4)回答要点通过实现XxxListener接口或者继承XxxAdapter类实现一个事件监听器类,并对处理监听动作的方法进行重写1创立事件源对象和事件监听器对象1调用事件源的addXxxLisntener()方法,为事件源注册事件监听器对象(5)回答要点JavaAWT里面的事件可以简单的分为窗体事件(WindowEvent),鼠标事件(MouseEvent), 键盘事件(KeyEvent),动作事件(ActionEvent)等事件。

java第七版课后答案——第二章

java第七版课后答案——第二章

//******************************************************************** // AverageOfThree.java Author: Lewis/Loftus//// Solution to Programming Project 2.2//******************************************************************** import java.util.Scanner;public class AverageOfThree{//----------------------------------------------------------------- // Reads three integers from the user and prints their average.//----------------------------------------------------------------- public static void main (String[] args){int num1, num2, num3;double average;Scanner scan = new Scanner (System.in);System.out.print ("Enter the first number: ");num1 = scan.nextInt();System.out.print ("Enter the second number: ");num2 = scan.nextInt();System.out.print ("Enter the third number: ");num3 = scan.nextInt();average = (double) (num1+num2+num3) / 3;System.out.println ("The average is: " + average);}}//******************************************************************** // AverageOfThree2.java Author: Lewis/Loftus//// Alternate solution to Programming Project 2.2//******************************************************************** import java.util.Scanner;public class AverageOfThree2{//----------------------------------------------------------------- // Reads three integers from the user and prints their average.//----------------------------------------------------------------- public static void main (String[] args){int num1, num2, num3;double average;Scanner scan = new Scanner (System.in);System.out.print ("Enter three numbers: ");num1 = scan.nextInt();num2 = scan.nextInt();num3 = scan.nextInt();average = (double) (num1+num2+num3) / 3;System.out.println ("The average is: " + average);}}//******************************************************************** // Balloons.java Author: Lewis/Loftus//// Solution to Programming Project 2.17//********************************************************************import javax.swing.JApplet;import java.awt.*;public class Balloons extends JApplet{//----------------------------------------------------------------- // Draws a set of balloons on strings.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.white);// draw the stringspage.setColor (Color.black);page.drawLine (45, 95, 100, 300);page.drawLine (90, 100, 100, 300);page.drawLine (60, 100, 100, 300);page.drawLine (122, 85, 100, 300);page.drawLine (145, 115, 100, 300);// draw the balloonspage.setColor (Color.blue);page.fillOval (20, 30, 50, 65);page.setColor (Color.yellow);page.fillOval (70, 40, 40, 60);page.setColor (Color.red);page.fillOval (40, 50, 40, 55);page.setColor (Color.green);page.fillOval (100, 30, 45, 55);page.setColor (Color.cyan);page.fillOval (120, 55, 50, 60);}}//******************************************************************** // BigDipper.java Author: Lewis/Loftus//// Solution to Programming Project 2.16//********************************************************************import javax.swing.JApplet;import java.awt.*;public class BigDipper extends JApplet{//----------------------------------------------------------------- // Draws the Big Dipper constellation and some other stars.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.black);page.setColor (Color.white);page.drawLine (100, 80, 110, 120);page.drawLine (110, 120, 165, 115);page.drawLine (165, 115, 175, 70);page.drawLine (100, 80, 175, 70);page.drawLine (175, 70, 245, 20);page.drawLine (245, 20, 280, 30);// Draw some extra starspage.fillOval (50, 50, 4, 4);page.fillOval (70, 150, 3, 3);page.fillOval (90, 30, 3, 3);page.fillOval (220, 140, 4, 4);page.fillOval (280, 170, 3, 3);page.fillOval (310, 100, 4, 4);page.fillOval (360, 20, 3, 3);}}//******************************************************************** // BusinessCard.java Author: Lewis/Loftus//// Solution to Programming Project 2.20//********************************************************************import javax.swing.JApplet;import java.awt.*;public class BusinessCard extends JApplet{//----------------------------------------------------------------- // Draws a business card.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.yellow);page.setColor (Color.red);page.fillOval (10, 20, 60, 60);page.setColor (Color.cyan);page.fillRect (25, 35, 130, 25);page.setColor (Color.black);page.drawString ("James C. Kerplunk", 35, 50);page.drawString ("President and CEO", 85, 80);page.drawString ("Origin Software, Inc.", 85, 100);page.drawLine (225, 20, 225, 80);page.drawLine (195, 50, 255, 50);page.setColor (Color.blue);page.drawString ("where it all begins...", 115, 135);}}//******************************************************************** // ChangeCounter.java Author: Lewis/Loftus//// Solution to Programming Project 2.10//******************************************************************** import java.util.Scanner;public class ChangeCounter{//----------------------------------------------------------------- // Computes the total value of a collection of coins.//----------------------------------------------------------------- public static void main (String[] args){int quarters, dimes, nickels, pennies;int total, dollars, cents;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of quarters: ");quarters = scan.nextInt();System.out.print ("Enter the number of dimes: ");dimes = scan.nextInt();System.out.print ("Enter the number of nickels: ");nickels = scan.nextInt();System.out.print ("Enter the number of pennies: ");pennies = scan.nextInt();total = quarters * 25 + dimes * 10 + nickels * 5 + pennies;dollars = total / 100;cents = total % 100;System.out.println ("Total value: " + dollars + " dollars and " + cents + " cents.");}}//******************************************************************** // DrawName.java Author: Lewis/Loftus//// Solution to Programming Project 2.15//********************************************************************import javax.swing.JApplet;import java.awt.*;public class DrawName extends JApplet{//----------------------------------------------------------------- // Draws a name.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.cyan);page.setColor (Color.black);page.drawString ("John A. Lewis", 50, 50);}}//******************************************************************** // FloatCalculations.java Author: Lewis/Loftus//// Solution to Programming Project 2.4//******************************************************************** import java.util.Scanner;public class FloatCalculations{//----------------------------------------------------------------- // Reads two floating point numbers and prints their sum,// difference, and product.//----------------------------------------------------------------- public static void main (String[] args){float num1, num2;Scanner scan = new Scanner (System.in);System.out.print ("Enter the first number: ");num1 = scan.nextFloat();System.out.print ("Enter the second number: ");num2 = scan.nextFloat();System.out.println ("Their sum is: " + (num1+num2));System.out.println ("Their difference is: " + (num1-num2));System.out.println ("Their product is: " + (num1*num2));}}//******************************************************************** // Fraction.java Author: Lewis/Loftus//// Solution to Programming Project 2.13//******************************************************************** import java.util.Scanner;public class Fraction{//----------------------------------------------------------------- // Computes the floating point equivalent of a fraction.//----------------------------------------------------------------- public static void main (String[] args){int numerator, denominator;float value;Scanner scan = new Scanner(System.in);System.out.print ("Enter the numerator: ");numerator = scan.nextInt();System.out.print ("Enter the denominator: ");denominator = scan.nextInt();value = (float) numerator / denominator;System.out.println ("Floating point equivalent: " + value);}}//******************************************************************** // HousePicture.java Author: Lewis/Loftus//// Solution to Programming Project 2.19//********************************************************************import javax.swing.JApplet;import java.awt.*;public class HousePicture extends JApplet{//----------------------------------------------------------------- // Draws a house scene.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.cyan);page.setColor (Color.gray);page.fillRect (0, 200, 400, 50); // groundpage.setColor (Color.blue);page.fillRect (50, 125, 300, 100); // housepage.setColor (Color.green);page.fillRect (180, 175, 40, 50); // doorpage.setColor (Color.yellow);page.fillRect (100, 155, 40, 25); // windowpage.fillRect (260, 155, 40, 25); // windowpage.setColor (Color.black);page.fillRect (40, 100, 320, 40); // roofpage.fillOval (210, 200, 6, 6); // doorknobpage.setColor (Color.red);page.fillRect (80, 80, 20, 40); // chimneypage.setColor (Color.darkGray);page.fillOval (80, 60, 20, 20); // smokepage.fillOval (85, 50, 15, 25); // smokepage.fillOval (90, 45, 15, 20); // smokepage.setColor (Color.white);page.fillOval (200, 30, 80, 40); // cloudpage.fillOval (230, 40, 80, 40); // cloud}}//******************************************************************** // InfoParagraph.java Author: Lewis/Loftus//// Solution to Programming Project 2.3//********************************************************************import java.util.Scanner;public class InfoParagraph{//----------------------------------------------------------------- // Reads information about a person and incorporates it into an// output paragraph.//----------------------------------------------------------------- public static void main (String[] args){String name, age, college, pet;Scanner scan = new Scanner (System.in);System.out.print ("What is your name? ");name = scan.nextLine();System.out.print ("How old are you? ");age = scan.nextLine();System.out.print ("What college do you attend? ");college = scan.nextLine();System.out.print ("What is your pet's name? ");pet = scan.nextLine();System.out.println ();System.out.print ("Hello, my name is " + name + " and I am ");System.out.print (age + " years\nold. I'm enjoying my time at "); System.out.print (college + ", though\nI miss my pet " + pet);System.out.println (" very much!");System.out.println ();}}//******************************************************************** // Lincoln4.java Author: Lewis/Loftus//// Solution to Programming Project 2.1//********************************************************************public class Lincoln4{//----------------------------------------------------------------- // Prints a quote from Abraham Lincoln, including quotation// marks.//----------------------------------------------------------------- public static void main (String[] args){System.out.println ("A quote by Abraham Lincoln:");System.out.println ("\"Whatever you are, be a good one.\"");}}//******************************************************************** // MilesToKilometers.java Author: Lewis/Loftus//// Solution to Programming Project 2.6//******************************************************************** import java.util.Scanner;public class MilesToKilometers{//----------------------------------------------------------------- // Converts miles into kilometers. The value for miles is read// from the user.//----------------------------------------------------------------- public static void main (String[] args){final double MILES_PER_KILOMETER = 1.60935;double miles, kilometers;Scanner scan = new Scanner(System.in);System.out.print ("Enter the distance in miles: ");miles = scan.nextDouble();kilometers = MILES_PER_KILOMETER * miles;System.out.println ("That distance in kilometers is: " +kilometers);}}//******************************************************************** // MoneyConversion.java Author: Lewis/Loftus//// Solution to Programming Project 2.11//******************************************************************** import java.util.Scanner;public class MoneyConversion{//----------------------------------------------------------------- // Reads a monetary amount and computes the equivalent in bills// and coins.//----------------------------------------------------------------- public static void main (String[] args){double total;int tens, fives, ones, quarters, dimes, nickels;int remainingCents;Scanner scan = new Scanner(System.in);System.out.print ("Enter monetary amount: ");total = scan.nextDouble();remainingCents = (int) (total * 100);tens = remainingCents / 1000;remainingCents %= 1000;fives = remainingCents / 500;remainingCents %= 500;ones = remainingCents / 100;remainingCents %= 100;quarters = remainingCents / 25;remainingCents %= 25;dimes = remainingCents / 10;remainingCents %= 10;nickels = remainingCents / 5;remainingCents %= 5;System.out.println ("That's equivalent to:");System.out.println (tens + " ten dollar bills");System.out.println (fives + " five dollar bills");System.out.println (ones + " one dollar bills");System.out.println (quarters + " quarters");System.out.println (dimes + " dimes");System.out.println (nickels + " nickels");System.out.println (remainingCents + " pennies");}}//******************************************************************** // OlympicRings.java Author: Lewis/Loftus//// Solution to Programming Project 2.18//********************************************************************import javax.swing.JApplet;import java.awt.*;public class OlympicRings extends JApplet{//----------------------------------------------------------------- // Draws the olympic logo.//----------------------------------------------------------------- public void paint (Graphics page){final int DIAMETER = 50;setBackground (Color.lightGray);page.setColor (Color.blue);page.drawOval (30, 40, DIAMETER, DIAMETER);page.setColor (Color.yellow);page.drawOval (60, 70, DIAMETER, DIAMETER);page.setColor (Color.black);page.drawOval (90, 40, DIAMETER, DIAMETER);page.setColor (Color.green);page.drawOval (120, 70, DIAMETER, DIAMETER);page.setColor (Color.red);page.drawOval (150, 40, DIAMETER, DIAMETER);}}//******************************************************************** // PieChart.java Author: Lewis/Loftus//// Solution to Programming Project 2.22//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class PieChart extends JApplet{//----------------------------------------------------------------- // Draws the pie chart with equal sections.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.lightGray);page.setColor (Color.blue);page.fillArc (70, 25, 100, 100, 0, 45);page.setColor (Color.yellow);page.fillArc (70, 25, 100, 100, 45, 45);page.setColor (Color.black);page.fillArc (70, 25, 100, 100, 90, 45);page.setColor (Color.green);page.fillArc (70, 25, 100, 100, 135, 45);page.setColor (Color.red);page.fillArc (70, 25, 100, 100, 180, 45);page.setColor (Color.magenta);page.fillArc (70, 25, 100, 100, 225, 45);page.setColor (Color.cyan);page.fillArc (70, 25, 100, 100, 270, 45);page.setColor (Color.orange);page.fillArc (70, 25, 100, 100, 315, 45);}}//******************************************************************** // Seconds.java Author: Lewis/Loftus//// Solution to Programming Project 2.8//******************************************************************** import java.util.Scanner;public class Seconds{//----------------------------------------------------------------- // Computes the total number of seconds for a given number of// hours, minutes, and seconds.//-----------------------------------------------------------------public static void main (String[] args){final int SECONDS_PER_HOUR = 3600;final int SECONDS_PER_MINUTE = 60;int seconds, minutes, hours, totalSeconds;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of hours: ");hours = scan.nextInt();System.out.print ("Enter the number of minutes: ");minutes = scan.nextInt();System.out.print ("Enter the number of seconds: ");seconds = scan.nextInt();totalSeconds = hours * SECONDS_PER_HOUR +minutes * SECONDS_PER_MINUTE +seconds;System.out.println ();System.out.println ("Total seconds: " + totalSeconds);}}//******************************************************************** // Seconds2.java Author: Lewis/Loftus//// Solution to Programming Project 2.9//******************************************************************** import java.util.Scanner;public class Seconds2{//----------------------------------------------------------------- // Computes the number of hours, minutes, and seconds that are// equivalent to the number of seconds entered by the user.//----------------------------------------------------------------- public static void main (String[] args){final int SECONDS_PER_HOUR = 3600;final int SECONDS_PER_MINUTE = 60;int seconds, minutes, hours;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of seconds: ");seconds = scan.nextInt();hours = seconds / SECONDS_PER_HOUR;seconds = seconds % SECONDS_PER_HOUR; // remaining secondsminutes = seconds / SECONDS_PER_MINUTE;seconds = seconds % SECONDS_PER_MINUTE; // remaining secondsSystem.out.println ();System.out.println ("Hours: " + hours);System.out.println ("Minutes: " + minutes);System.out.println ("Seconds: " + seconds);}}//******************************************************************** // ShadowName.java Author: Lewis/Loftus//// Solution to Programming Project 2.21//********************************************************************import javax.swing.JApplet;import java.awt.*;public class ShadowName extends JApplet{//----------------------------------------------------------------- // Draws a name with a slightly offset shadow.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.yellow);page.setColor (Color.black);page.drawString ("John A. Lewis", 50, 50);page.setColor (Color.red);page.drawString ("John A. Lewis", 49, 49);}}//******************************************************************** // Snowman2.java Author: Lewis/Loftus//// Solution to Programming Project 2.14//********************************************************************import javax.swing.JApplet;import java.awt.*;public class Snowman2 extends JApplet{//----------------------------------------------------------------- // Draws a snowman with added features.//----------------------------------------------------------------- public void paint (Graphics page){final int MID = 130;final int TOP = 50;setBackground (Color.cyan);page.setColor (Color.blue);page.fillRect (0, 175, 300, 50); // groundpage.setColor (Color.yellow);page.fillOval (260, -40, 80, 80); // sunpage.setColor (Color.white);page.fillOval (MID-20, TOP, 40, 40); // headpage.fillOval (MID-35, TOP+35, 70, 50); // upper torsopage.fillOval (MID-50, TOP+80, 100, 60); // lower torsopage.setColor (Color.red);page.fillOval (MID-3, TOP+50, 6, 6); // buttonpage.fillOval (MID-3, TOP+60, 6, 6); // buttonpage.setColor (Color.black);page.fillOval (MID-10, TOP+10, 5, 5); // left eyepage.fillOval (MID+5, TOP+10, 5, 5); // right eyepage.drawArc (MID-10, TOP+20, 20, 10, 10, 160); // frownpage.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left armpage.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right armpage.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hatpage.fillRect (MID-15, TOP-20, 30, 25); // top of hatpage.drawString ("John Lewis", 20, 20); // artist}}//******************************************************************** // SquareCalculations.java Author: Lewis/Loftus//// Solution to Programming Project 2.12//******************************************************************** import java.util.Scanner;public class SquareCalculations{//----------------------------------------------------------------- // Computes a square's perimeter and area given the length of// one side.//----------------------------------------------------------------- public static void main (String[] args){int side, perimeter, area;Scanner scan = new Scanner(System.in);System.out.print ("Enter the length of a square's side: ");side = scan.nextInt();perimeter = side * 4;area = side * side;System.out.println ("Perimeter: " + perimeter);System.out.println ("Area: " + area);}}//********************************************************************// TempConverter2.java Author: Lewis/Loftus//// Solution to Programming Project 2.5//******************************************************************** import java.util.Scanner;public class TempConverter2{//----------------------------------------------------------------- // Computes the Celsius equivalent of a Fahrenheit value read// from the user. Uses the formula C = (5/9)(F - 32).//----------------------------------------------------------------- public static void main (String[] args){final int BASE = 32;final double CONVERSION_FACTOR = 5.0 / 9.0;double celsiusTemp, fahrenheitTemp;Scanner scan = new Scanner(System.in);System.out.print ("Enter a Fahrenheit temperature: ");fahrenheitTemp = scan.nextDouble();celsiusTemp = CONVERSION_FACTOR * (fahrenheitTemp - BASE);System.out.println ("Celsius Equivalent: " + celsiusTemp);}}//******************************************************************** // TravelTime.java Author: Lewis/Loftus//// Solution to Programming Project 2.7//******************************************************************** import java.util.Scanner;public class TravelTime{//----------------------------------------------------------------- // Converts miles into kilometers. The value for miles is read// from the user.//-----------------------------------------------------------------public static void main (String[] args){int speed, distance;double time;Scanner scan = new Scanner(System.in);System.out.print ("Enter the speed: ");speed = scan.nextInt();System.out.print ("Enter the distance traveled: ");distance = scan.nextInt();time = (double) distance / speed;System.out.println ("Time elapsed during trip: " + time); }}。

JAVA习题集(含答案)

JAVA习题集(含答案)

JAVA习题集(含答案)习题一:1. 简述Java的发展过程。

2. 什么是软件?3. 什么叫做源程序?4. 什么叫做编译?5. 什么是Java的byte-codes?它的最大好处是什么?6. 机器语言程序、高级语言程序以及可表示成Java字节码的程序之间的区别是什么?7. Java程序可分为哪两种?分别如何运行?& 试简述J2SE、J2ME与J2EE的简单区别。

9. 练习使用浏览器查看Java API文档。

10. SDK的编译命令是什么?11. 试修改例1-1程序,使其输出的字符串为“I'd like to study Jave”!,并在DOS命令行环境下编译与运行该程序。

习题一参考答案:1. 答:1991: Sun Microsystems公司进军消费电子产品(IA)市场。

1991. 4:Sun成立“ Green”小组,以C++为基础开发新的程序设计语言,并将其命名为Oak。

1992. 10:Green小组升格为First Person公司,他们将Oak的技术转移到Web上,并把Oak改名为Java。

1993~1994: Web在In ternet上开始流行,致使Java得以迅速发展并获得成功。

1995. 5:Sun Microsystems 公司正式发表Java与HotJava 产品。

1995. 10:Netscape与Sun Microsystems 合作,在Netscape Nevigator 中支持Java。

1995. 12:微软(Microsoft )IE加入支持Java的行列。

1996. 2:Java Beta测试版结束,Java 1.0版正式诞生。

1997. 2:Java发展至1.1 版。

Java的第一个开发包JDK (Java Development Kit)发布。

1999. 7:Java升级至1.2版。

2000. 9:Java升级至1.3版。

2001. 7:Java升级至1.4版。

Java应用开发技术相关的测试题及参考解答(第6部分)

Java应用开发技术相关的测试题及参考解答(第6部分)
答案:AC
27、给出以下代码,请问以下描述正确的是? public XXXX extends something1,something2 A. 如果 XXXX 是一个接口,something1 和 something2 取消掉,则代码段合法 B. 如果 XXXX 是一个类,something1 和 something2 均是接口,则代码段合法 C. 如果 XXXX、something1 和 something2 都是接口,则代码段合法 D. 因为 Java 语音不支持多继承机制,所以代码段不合法
答案:C
28、给出以下代码,请问以下关于一个实现该接口的类的哪些描述是正确的? public interface Example{ void someMethod(); } A. 该类应该有一个被声明为 public 的 someMethod()方法 B. 该类应该有一个被声明为 public 的或不加任何访问修饰符的 someMethod()方法 C. 该类应该有一个不抛出异常的 someMethod()方法
杨教授工作室 精心创作的优秀程序员 职业提升必读系列资料
25、请问,以下哪些实现了多态? A. 内部类 B. 匿名类 C. 方法过载(override) D. 方法重载
答案:CD
26、请问以下哪些描述是正确的? A. native 关键字表明修饰的方法是有其他非 Java 语音编写的 B. 能够出现在 Java 源文件中 import 语句前的只有注释语句 C. 接口中定义的方法默认是 public 和 abstract 的,不能被 private 或 protected 修饰 D. 构造器只能被 public 或 protected 修饰
答案:A
24、请问,以下哪些有关接口的描述是正确的? A. 在接口中定义的方法默认都是 public 的 B. 在接口中定义的方法默认是 public、static、final 方法 C. 一个接口可以继承多个接口 D. 关键字 implements 代表继承关系

Java7课后习题

Java7课后习题

Java07课后习题一、选择题:1.下面关于访问文件和目录说法错误的一项是(C)。

A、File类虽然它不能访问文件内容,却可以用来进行文件的相关操作,它描述的是文件本身的属性。

B、File类如果需要访问文件本身,则需要使用输入/输出流。

C、File类可以使用文件路径字符串来创建File实例,该文件路径字符串可以是绝对路径,但不可以是相对路径,默认情况下,程序会根据用户的工作路径来解释相对路径,通常就是Java虚拟机所在的路径。

(也可以是相对路径)D、将路径当作File类来处理,路径名中除了最后一个之外每个字段都表示一个目录;最后一个字段可能表示一个目录或文件名。

2.下面关于流的描述有误的一项是( A )。

A、流是指一连串流动的字符,是以先进后出的方式发送信息的通道。

B、在Java中,处理字节流的两个基础的类是InputStream和OutputStream。

C、在Java中,用于处理字符流的两个基础的类是Reader和Writer。

D、按照流的方向分,可以分为输入流(Input Stream)和输出流(Output Stream)。

3.下面关于流的分类说法错误的一项是( B )。

A、为了处理Unicode字符串,定义了一系列的单独类,这些类是从抽象类Reader和Writer继承而来的。

B、这些单独类的操作均以单字节(16-bits)的Unicode字符为基础,而非双字节的字符为基础。

C、处理流是“处理流的流”,它用来处理其它的流,处理流又被称为高级流(High LevelStream)。

D、节点流又常常被称为低级流(Low Level Stream)。

4.下面关于低级InputStream类(节点流)的说法有误的一项是( D )。

A、低级InputStream类(节点流)的ByteArrayInputStream方法为读取字节数组设计的流,允许内存的一个缓冲区被当作InputStream使用。

Java程序设计实验指导书(答案)

Java程序设计实验指导书(答案)

第Ⅰ部分:实验指导实验1:Java开发环境J2SE一、实验目的(1)学习从网络上下载并安装J2SE开发工具。

(2)学习编写简单的Java Application程序.(3)了解Java源代码、字节码文件,掌握Java程序的编辑、编译和运行过程。

二、实验任务从网络上下载或从CD-ROM直接安装J2SE开发工具,编写简单的Java Application程序,编译并运行这个程序。

三、实验内容1.安装J2SE开发工具Sun公司为所有的java程序员提供了一套免费的java开发和运行环境,取名为Java 2 SDK,可以从上进行下载。

安装的时候可以选择安装到任意的硬盘驱动器上,例如安装到C:\j2sdk1.4.1_03目录下。

教师通过大屏幕演示J2SE的安装过程,以及在Windows98/2000/2003下环境变量的设置方法。

2.安装J2SE源代码编辑工具Edit Plus教师通过大屏幕演示Edit Plus的安装过程,以及在Windows98/2000/2003操作系统环境下编辑Java 原程序的常用命令的用法。

3.编写并编译、运行一个Java Application程序。

创建一个名为HelloWorldApp的java Application程序,在屏幕上简单的显示一句话"老师,你好!"。

public class HelloWorldApp{public static void main(String[] args){System.out.println("老师,你好!");}}4.编译并运行下面的Java Application程序,写出运行结果。

1:public class MyClass {2:private int day;3:private int month;4:private int year;5:public MyClass() {6:day = 1;7:month = 1;8:year = 1900;9:}10:public MyClass(int d,int m,int y) {11:day = d;12:month = m;13:year = y;14:}15:public void display(){16:System.out.println(day + "-" + month + "-" + year);17:}18:public static void main(String args[ ]) {19:MyClass m1 = new MyClass();20:MyClass m2 = new MyClass(25,12,2001);21:m1.display();22:m2.display();23:}24:}运行结果:1-1-190025-12-2001实验2:Java基本数据类型一、实验目的(1)掌握javadoc文档化工具的使用方法。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验7 1. 编一个程序,包含以下文件。

(1)Shape.java文件,在该文件中定义接口Shape,该接口在shape包中。

属性:PI。

方法:求面积的方法area()。

(2)Circle.java文件,在该文件中定义圆类Circle,该类在circle包中,实现Shape接口。

属性:圆半径radius。

方法:构造方法;实现接口中求面积方法area();求周长方法perimeter()。

(3)“Cylinder.java”文件,在该文件中定义圆柱体类Cylinder,该类口在cylinder包中,继承圆类。

属性:圆柱体高度height。

(4main(),}第三步:创建主类,在其中的main()方法中创建对象,实现相应的功能。

// X5_3_6.java文件package p3;import p2.*;public class X5_3_6 { // 定义主类public static void main(String[] args) {…}}【参考程序】// X5_3_6.java文件package p3;import p2.*;public class X5_3_6 { // 定义主类public static void main(String[] args) {Circle cir1 = new Circle(120.5);Circle cir2 = new Circle(183.8);r1.area());Cylinder cy1 = new Cylinder(27.3,32.7);Cylinder cy2 = new Cylinder(133.5,155.8);}}}}public class Cylinder extends Circle{ // 创建继承Circle类的Cylinder类double height;public Cylinder(double r,double h){super(r);height = h;}public double area(){return 2*PI*radius*radius+2*PI*radius*height;}public double volume(){return PI*radius*radius*height;}}2)定义一个接口OneToN,在接口中包含一个抽象方法disp()。

定义Sum和Pro类,并分别用不同代码实现ONeToN的disp()方法,在Sum的方法中计算1~n的和,在Pro的方法中计算1~n的乘积interface OneToN{public void disp(int n);}class Sum implements OneToN{public void disp(int n){}}{{}}x.disp(100);}}3)改错,上传正确答案,并以注释形式给出错误原因class SuperClass{public SuperClass(String msg)}class SubClass extends SuperClass{public SubClass(String msg){Super(msg); //父类没有无参的构造方法,应采用super显示调用父类的构造方法}}public class Test1 {public static void main(String[] args) {SubClass descendent = new SubClass();}}4)利用多态性编程,创建一个抽象类shape类,定义一个函数Area为求面积的公共方法,再定义Triangle,Rectangle和circle类,实现computerArea方法;增加display方法,显示name和area,并在Triangle,Rectangle和circle类覆盖该方法,并为每个类增加自己的构造方法;在主类中创建1AC2A.C.3AC4}A.ArithmeticException B.NumberFormatExceptionC.ArrayIndexOutOfBoundsException D.IOException【解析】当程序执行到“int y = 5/x”语句时,发生异常,程序中止执行,因此发生ArithmeticException 异常。

5.运行下面程序时,会产生什么异常?( C )public class X7_1_5 {public static void main(String[] args) {int[] z = {1,2,3,4};int p = z[4];int x = 0;int y = 5/x;}}A.ArithmeticException B.NumberFormatExceptionC.ArrayIndexOutOfBoundsException D.IOException【解析】当程序执行到“int p = z[4]”语句时,发生异常,程序中止执行,因此发生ArrayIndexOutOfBoundsException异常。

6.下列程序执行的结果是( B )。

public class X7_1_6 {public static void main(String[] args) {try{return;}finally{}}AC7A.C.”8ABCD1public static void main(String[] args){int[] a = new int[-5];for(int i=0; i<a.length; i++){a[i] = 10 + i;}}}【运行结果】at X7_3_1.main(X7_3_1.java:3)2.编写一个由throw抛出的、系统自行处理的数组下标越界的程序。

【编程分析】当由throw抛出异常后,如果程序本身不进行异常处理,Java系统将采用默认的处理方式进行处理。

【参考程序】import java.io.*;public class X7_3_2 {public static void main(String[] args)throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);int[] a = new int[5];int n = Integer.parseInt(br.readLine());}83对象,则在try{ // 当输入的b为0时,就会出现算术异常}catch(ArithmeticException e){ // 捕捉算术异常并进行处理}int c[] =new int[4], sum = 0;try{ // 当出现数组下标越界时就会抛出异常for(int i = 0; i<5; i++) sum += c[i];" + sum);}catch(ArrayIndexOutOfBoundsException e){// 捕捉数组下标越界异常并处理}}}【运行结果】请输入两个整数:20出现被0除的情况!数组下标越界!4.编写一个由throw抛出的、由try-catch捕捉处理的分母为0以及数组下标越界的程序。

【编程分析】当在程序出现异常之前利用throw语句来抛出异常,可以做到防患于未然,提前进行异常处理,将由被动处理异常转变为主动防止异常发生。

");catch(ArrayIndexOutOfBoundsException e){e.printStackTrace();}}}5.自定义两个异常类NumberTooBigException和NumberTooSmallException,在其中定义各自的构造方法,分别打印输出“发生数字太大异常”和“发生数字太小异常”。

然后在主类中定义一个带throws的方法numberException(int x),当x>100时通过throw抛出NumberTooBigException异常,当x<0时通过throw抛出NumberTooSmallException异常;最后在main()方法中调用该方法,实现从键盘中输入一个整数,如果输入的是负数,引发NumberTooSmallException异常,如果输入的数大于100,引发。

NumberTooBigException异常,否则输出“没有发生异常”。

【编程分析】本题主要考察自定义异常的方法。

第一步:定义异常类NumberTooBigExceptionclass NumberTooBigException extends Exception{NumberTooBigException(){super("发生数字太大异常");}}第二步:定义异常类NumberTooSmallExceptionclass NumberTooSmallException extends Exception{NumberTooSmallException(){super("发生数字太小异常");}}e.printStackTrace();}}public static void numberException(int x) throws NumberTooBigException, NumberTooSmallException{if(x>100)throw new NumberTooBigException();else if (x<0)throw new NumberTooSmallException();else}}class NumberTooBigException extends Exception{NumberTooBigException(){super("发生数字太大异常");}}class NumberTooSmallException extends Exception{NumberTooSmallException(){super("发生数字太小异常");}}实验91ABCD2A.3.A.5A.6ABCD7A.KeyEvent B.ActionEvent C.ItemEvent D.MouseEvent 【解析】对鼠标操作,触发的事件是MouseEvent事件。

8.下列哪一项不属于Swing的顶层组件( C )?A.JApplet B.JDialog C.JTree D.Jframe【解析】JTree 只有在容器中才能显示,它不属于swing的顶层组件。

相关文档
最新文档