JAVA实验报告

更新时间:2024-06-23 20:34:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

学 生 实 验 报 告 册

(理工类)

课程名称:面向对象程序设计 专业班级:16计算机科学与技术(专转本)

学生学号: 1613203022 学生姓名: 张义丹

所属院部: 计算机工程 指导教师: 刘 晶

20 16 ——20 17 学年 第 2 学期

金陵科技学院教务处制

实验报告书写要求

实验报告上交电子稿,标题采用四号黑体,正文采用小四号宋体,单倍行距。

实验报告书写说明

实验报告中实验目的和要求、实验仪器和设备、实验内容与过程、实验结果与分析这四项内容为必需项。教师可根据学科特点和实验具体要求增加项目。

填写注意事项

(1)细致观察,及时、准确、如实记录。 (2)准确说明,层次清晰。

(3)尽量采用专用术语来说明事物。

(4)外文、符号、公式要准确,应使用统一规定的名词和符号。 (5)应独立完成实验报告的书写,严禁抄袭、复印,一经发现,以零分论处。

实验报告批改说明

实验报告的批改要及时、认真、仔细,一律用红色笔批改。实验报告的批改成绩采用五级记分制或百分制,按《金陵科技学院课堂教学实施细则》中作业批阅成绩评定要求执行。

实验项目名称:Java编程基础 实验学时: 6 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.3.21~17.4.4 实验成绩: 批改教师: 刘晶 批改时间:

1

实验1 Java编程基础

一、实验目的和要求

(1) 熟练掌握JDK1.6及Eclipse4.2编写调试Java应用程序及Java小程序的方法; (2) 熟练掌握Java应用程序的结构;

(3) 了解Java语言的特点,基本语句、运算符及表达式的使用方法; (4) 熟练掌握常见数据类型的使用;

(5) 熟练掌握if-else、switch、while、do-while、for、continue、break、return

语句的使用方法;

(6) 熟练掌握数组和字符串的使用;

(7) 调试程序要记录调试过程中出现的问题及解决办法;

(8) 编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试

经验;

(9) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。

三、实验过程

(1)分别使用JDK命令行和Eclipse编译运行Java应用程序;适当添加注释信息,通过javadoc生成注释文档;为主方法传递参数“Hello world”字符串,并输出,记录操作过程。

public class Hello {

public static void main(String args[]) {

System.out.println(\ } } (2)分别使用JDK命令行和Eclipse编译Java Applet,并建立HTML文档运行该Applet。压缩生成\文件。记录操作过程。 import java.awt.*;

import java.applet.Applet;

public class HelloApplet extends Applet {

public void paint(Graphics g) {

g.setColor(Color.red);

g.drawString(\ }

2

}

(3) 根据变量score中存放的考试分数,输出对应的等级。要求从键盘输入学生成绩, 60分以下为D等;60~69为C等;70~89为B等;90~100为A等。 (4) 编写一个Java Application程序,输出区间[200,300]上的所有素数,将其用数组prime[]保存,并以每10个一行的形式显示运行结果。 (5)输出下列数字形式,要求用二维数组完成。 ①n=4

0 0 0 0 0 1 1 1 0 1 2 2 0 1 2 3 ② n=4

1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1

(6) 求二维数组的鞍点,即该位置上的元素在该行上最大,在列上最小。也可能无鞍点。 (7) 分析下列程序的输出结果,掌握equals()方法和“= =”的区别。 class StringTest2{ public static void main(String args[]) { String s1 = \ String s2 = \ String s3 = new String(\ String s4 = new String(s1); String s5 = s1; boolean result121 = s1.equals(s2); boolean result122 = s1 == s2; boolean result131 = s1.equals(s3); boolean result132 = s1 == s3; boolean result141 = s1.equals(s4); boolean result142 = s1 == s4; boolean result151 = s1.equals(s5); boolean result152 = s1 == s5; System.out.println(\ System.out.println(\ System.out.println(\ System.out.println(\ System.out.println(\

3

System.out.println(\ System.out.println(\ System.out.println(\ } }

(8) 判断回文字符串

回文是一种“从前向后读”和“从后向前读”都相同的字符串。如“rotor”是一个回文字符串。

程序中使用了两种算法来判断回文字符串: 算法一:分别从前向后和从后向前依次获得原串str的一个字符ch1、ch2,比较ch1和ch2,如果不相等,则str肯定不是回文串,yes=false,立即退出循环:否则继续比较,直到字符全部比较完,yes的值仍为true,才能肯定str是回文串。

算法二:将原串str反转成temp串,再比较两串,如果相等则是回文字符串。 (9) 使用String类的compareTo(String s)方法,对以下字符串从小到大排序:“melon”, “apple”, “pear”, “banana”,显示输出排序结果。

要求:

(1) 编译调试程序之前应配置好环境变量;

(2) 要分别掌握用JDK命令行和Eclipse集成开发环境调试Java程序; (3) 注意Java两大类程序:应用程序和小程序的区别。

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。)

(1)主方法传递参数“Hello world”字符串,并输出

public class Hello { public Hello(){

System.out.println(\ }

public static void main(String args[]){ new Hello(); } }

(2)Eclipse编译Java Applet import java.awt.*;

import java.applet.Applet;

public class HelloApplet extends Applet { int height,width; public void init(){ this.height=100; this.width=300; }

4

public void paint(Graphics g){ g.setColor(Color.red);

g.drawString(\ } } (3)

package b;

import java.util.Scanner; public class Test {

public static void main(String args[]){ int score; //char grade;

System.out.println(\请输入分数按回车\ Scanner reader=new Scanner(System.in); score=reader.nextInt(); if(score>=90&&score<=100){ System.out.println(\ }

else if(score>=70&&score<=89){ System.out.println(\ }

else if(score>=60&&score<=69){ System.out.println(\ }

else if(score<60){

System.out.println(\ } else{

System.out.println(\数据错误\ } } } (4)

public class Lim {

public static void main(String[] args) { int[] prime = calculation(20, 200, 300); for (int i = 0; i < prime.length; i++) { if (prime[i] != 0) {

if (i % 10 == 0 && i != 0) System.out.println();

System.out.print(prime[i] + \打印数据 }

}

5

}

public static int[] calculation(int length, int start, int end) { int j;

int step = 0;

int[] prime = new int[length];

for (int i = start; i <= end; i++) {

j = 2;

while (i % j != 0) { j++; }

if (j == i) {

prime[step] = i; step++; } }

return prime;

} } (5)

① public class shuzu {

public static void main(String args[]){ int i,j;

int arr[][]=new int[4][]; for(i=0;i

arr[i]=new int[arr.length]; for(i=0;i<4;i++)

for(j=3;j>=i;j--){ arr[i][j]=i; }

for(j=0;j<4;j++){ for(i=3;i>=j;i--){ arr[i][j]=j; } }

for(i=0;i<=3;i++){ for(j=0;j<=3;j++){

System.out.print(arr[i][j]); System.out.print(\ }

System.out.println();

6

} } }

②public class Shuzu {

public static void main(String args[]){ int num[][]=new int[4][];

for(int i=0;i

for(int m=0;m

int k=i+1;

for(int j=0;j

num[i][j]=j+1; else{ k--;

num[i][j]=k; }

System.out.print(num[i][j]+\ }

System.out.println(); } } } (6)

public class test {

public static void main(String[] args) { // TODO Auto-generated method stub

int[][] mat = {{11,12,13},{4,5,6},{7,8,9}};

for (int i=0;i

for(int j=0;j

System.out.print(mat[i][j]+\ System.out.println(); }

boolean find = false; //找到鞍点标记 int row=0; //第1行下标

int max=0; //记录当前行最大值的列下标 while (!find && row

max=0; //初始设每行第1列值最大

for (int j=1;j

7

if (mat[row][j]>mat[row][max]) //mat[row][max]为该行最大值 max = j;

boolean yes = true; //再判断mat[row][max]是否在列上最小 int j=0;

while (yes && j

if(mat[j][max]

if (yes)

find = true; else row++; }

if (find)

System.out.println(\ else

System.out.println(\ } }

(8) import java.util.Scanner; public class HuiWenTest {

public static void main(String[] args) { // TODO Auto-generated method stub

System.out.println(\请输入一个字符串\ @SuppressWarnings(\

Scanner input = new Scanner(System.in); String str = input.next();

StringBuilder sb=new StringBuilder(str); sb.reverse();//将Sr倒置的方法 String newStr=new String(sb); if(str.equals(newStr)){

System.out.println(str+\是回文字符串\ }else{

System.out.println(str+\不是回文字符串\ } } }

(9) import java.util.*; public class SortString {

public static void main(String[] args) { // TODO Auto-generated method stub

String [ ] a={\

8

String [ ] b=Arrays.copyOf(a,a.length);

System.out.println(\使用用户编写的SortString类,按字典序排列数组a:\

SortString.sort(a);

System.out.println(\排序结果是:\ for(String s:a) {

System.out.print(\ }

System.out.println(\

System.out.println(\使用类库中的Arrays类,按字典序排列数组b:\

Arrays.sort(b);

System.out.println(\排序结果是:\ for(String s:b) {

System.out.print(\ } }

四、实验结果与分析(程序运行结果及其分析)

(1)

9

(2)

10

(3)

(4)

(5)

(6)

(7)

11

(8)

(9)

五、实验体会(遇到问题及解决办法,编程后的心得体会)

在这次实验中,我知道了eclipse和jdk运行程序的区别,jdk比较麻烦一些,需要配置变量。在实验中,配置jdk的环境变量要注意它的path和 classpath,如果classpath本身就有,可以在后面加分号,这样不影响其它的classpath的使用。学会了如何生成注释文档,主函数传递参数的方法,还有压缩文件,实验中还对数组的创建和使用进行了练习,还有一些类的应用。

12

实验项目名称: 面向对象编程 实验学时: 8 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.4.11~17.5.2 实验成绩: 批改教师: 刘晶 批改时间:

13

实验2 面向对象编程

一、实验目的和要求

(1)熟练掌握Java语言类定义的基本语法; (2)熟练掌握类成员的访问控制,对象建立的方法; (3)熟练掌握类构造方法、成员方法的定义和重载; (4)熟练掌握类继承、多态和抽象性; (5)熟练掌握接口的定义和实现方法; (6)掌握基本的异常处理方法;

(7)调试程序要记录调试过程中出现的问题及解决办法;

(8)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;

(9) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。

三、实验过程

(1)定义一个Man类,保存在Man.java文件中,类中包含说话方法如下: public class Man { public void say() { System.out.println(“我是中国人!”); } }

为此类打包为cn.edu.jit.chinese;再在Man.java文件所在路径下,创建一个China.java文件,其中定义China类如下: public class China { public static void main(String[] args) { Man lihua = new Man(); lihua.say(); } } 在China类中引用Man类,输出显示“我是中国人!”。试着去掉Man类的public修饰,看看会发生什么情况?

(2)设计复数类,成员变量包括实部和虚部,成员方法包括实现复数加法、减法、字符串描述、比较是否相等等操作。

14

(3)包的建立与使用:设计计算器类Calculator,计算加、减、乘、除和立方体体积,并且打包为mypackage。观察源文件目录下是否生成了mypackage文件夹,在该文件夹中是否有Calculate.class文件。编辑PackageDemo.java,保存在Calculator.java同一目录下,引用计算器类的各方法显示计算结果。

(4)试编码实现简单的银行业务:处理简单帐户存取款、查询。编写银行帐户类BankAccount,包含数据成员:余额(balance)、利率(interest);操作方法:查询余额、存款、取款、查询利率、设置利率。再编写主类UseAccount,包含main()方法,创建BankAccount类的对象,并完成相应操作。

(5)假定根据学生的3门学位课程的分数决定其是否可以拿到学位,对于本科生,如果3门课程的平均分数超过60分即表示通过,而对于研究生,则需要平均超过80分才能够通过。根据上述要求,请完成以下Java类的设计: 1)设计一个基类Student描述学生的共同特征。

2)设计一个描述本科生的类Undergraduate,该类继承并扩展Student类。 3)设计一个描述研究生的类Graduate,该类继承并扩展Student类。

4)设计一个测试类StudentDemo,分别创建本科生和研究生这两个类的对象,并输出相关信息。

(6)设计三角形类,继承图形抽象类,计算三角形面积和周长。

(7)试编码实现多态在工资系统中的应用:给出一个根据雇员类型利用abstract方法和多态性完成工资单计算的程序。Employee是抽象类,Employee的子类有Boss(每星期发给他固定工资,而不计工作时间)、CommissionWorker(除基本工资外还根据销售额发放浮动工资)、PieceWorker(按其生产的产品数发放工资)、HourlyWorker(根据工作时间长短发放工资)。该例的Employee的每个子类都声明为final,因为不需要再继承它们生成子类。在主测试类Test中测试各类雇员工资计算结果。

提示:对所有雇员类型都使用earnings()方法,但每个人挣的工资按他所属的雇员类

计算,所有雇员类都是从超类Employee派生出的。在超类中声明earnings()为抽象方法,并且对于每个子类都提供恰当的earnings()的实现方法。为了计算雇员的工资,程序仅仅使用雇员对象的一个超类引用并调用earnings()方法。在一个实际的工资系统中,各种Employee对象的引用可以通过一个Employee引用数组来实现。程序依次使用数组的每个元素(Employee引用)调用每个对象的earnings()方法。 Employee类定义如下: abstract class Employee {

private String firstName; private String lastName;

public Employee(String first,String last) {

15

firstName=first; lastName=last; }

public String getEmployeeName() {

return firstName; }

public String getLastName() {

return lastName; }

public String toString() {

return firstName+lastName; }

public abstract String earnings(); }

(8)设计圆柱体类和圆椎体类,继承圆类Circle并实现体积接口Volume,计算表面积和体积。

(9)定义一个接口CanFly,描述会飞的方法public void fly();分别定义飞机类和鸟类,实现CanFly接口。定义一个测试类,测试飞机和鸟。测试类中定义一个makeFly(CanFly obj)方法,让会飞的事物飞起来(即调用相应类的fly()方法)。然后在main方法中创建飞机对象和鸟对象,并在main方法中调用makeFly(CanFly obj)方法,让飞机和鸟起飞。

(10)异常的捕获:计算两数相除并输出结果。使用三个catch子句,分别捕捉输入输出异常、除数为0的异常和参数输入有误异常。 import java.io.*; class Ex1 {

public static void main(String args[ ]) {

try{

BufferedReader strin=new BufferedReader(

new InputStreamReader(System.in));//建立输入流缓冲区 System.out.print(\请输入除数:\

String cl=strin.readLine();//键盘输入 int a=Integer .parseInt(cl);

System .out .print(\请输入被除数:\ cl=strin .readLine();

int b=Integer .parseInt(cl); int c=b/a;

System .out .println(\商为:\ }

//捕获与I/O有关的异常(空白处补全捕获语句)

16

//捕获数值转化时的异常,如不能将字符转化成数值

//捕获除数为0的异常 } }

编译并运行,当产生输入输出异常时显示异常信息;当输入除数为0时,出现算术异常,提示除数为0,并要求重新输入;当输入的不是整数时,如将30输成了3o,出现数值格式异常,提示输入整数。

(11)编写程序包含自定义异常MyException,当100被13和4除时抛出该异常,其余除数显示商值。

要求:

(1) 注意选用适当的类成员修饰符(private、protected、public等),比较它们的使

用情况;

(2) 养成良好的编程习惯,严格按照命名规则为包、类及类成员命名,将每个程序打包,

包的命名方式如two.num1表示实验二的第一题;

(3) 学会使用Eclipse的各种调试方法;

(4) 学会查阅Java API文档,如查找异常类的使用方法。

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。) (1) package cn.edu.jit.chinese;// 为Man类打包为cn.edu.jit.chinese

public class Man { public void say() {

System.out.println(\我是中国人!\ } }

package cn.edu.jit.chinese;

import cn.edu.jit.chinese.*; //导入包

public class China {

public static void main(String[] args) {

Man lihua = new Man();//主方法先创建类然后调用类 lihua.say(); } }

(2)public class Complex {

private double real,image; //定义私有的real,image public Complex(double real,double image)

17

{this.real=real; //赋值

this.image=image;} public Complex(double real) {this(real,0);} public Complex() {this(0,0);}

public Complex(Complex c) {this(c.real,c.image);} public double getReal() {return real;}

public void setReal(double real) { this.real = real;}

public double getImage() { return image;}

public void setImage(double image) { this.image = image;}

public Complex add(Complex c1,Complex c2)//写方法

{Complex C=new Complex(c1.real+c2.real,c1.image+c2.image); return C;}

public Complex add(Complex c1) {Complex C=new

Complex(this.real+c1.real,this.image+c1.image); return C; }

public Complex jian(Complex c1,Complex c2)

{Complex C=new Complex(c1.real-c2.real,c1.image-c2.image); return C; }

public Complex jian(Complex c1)

{Complex C=new Complex(this.real-c1.real,this.image-c1.image); return C; }

public boolean bijiao(Complex c1,Complex c2)

{return (c1.real==c2.real&&c1.image==c2.image); }

public boolean bijiao(Complex c1)

{return (c1.real==this.real&&c1.image==this.image); }

public String toString()

{return this.real+\}

public class ComplexText {

public static void main(String[] args) {

Complex c1=new Complex(2,5); //创建类,调用类里面的方法

18

Complex c2=new Complex(5,2); Complex c3=new Complex();

System.out.println(c3.add(c1,c2)); System.out.println(c3.jian(c1,c2)); System.out.println(c3.bijiao(c1,c2));} }

(3)public class Calculate { double i,j, t;

public Calculate(int i,int j) {this.i=i; this.j=j;}

public Calculate(int i,int j,int t) {this.i=i;

this.j=j;this.t=t;} public double add() {return i+j;} public double jian() {return i-j;}

public double cheng() {return i*j;} public double chu()

{return i/j;} public double tiji()

{return i*i*i+j*j*j+t*t*t;} }

public class PackageDemo {//测试

public static void main(String[] args) { Calculate c1=new Calculate(8,4); Calculate c2=new Calculate(8,4,2);

System.out.println(\相加=\ System.out.println(\相减=\ System.out.println(\相乘=\ System.out.println(\相除 =\

System.out.println(\立方体体积=\ }

(4)public class BankAccount {

double balance,interest,cunkuan;

public BankAccount(double cunkuan,double balance)//写方法 {this.balance=balance; this.cunkuan=cunkuan;} public void set(double cunkuan)

19

{if(cunkuan<10000) interest=0.1;

else if(cunkuan<50000) interest=0.25; else if(cunkuan<100000) interest=0.035; else interest=0.5; }

public double get() { return interest;}

public void chaxun(double balance,double cunkuan) {System.out.println(\存款为:\ System.out.println(\余额为:\ public void qu(double qukuan)

{System.out.println(\取款为:\ System.out.println(\得到的利润率:\ }

public class UseAccount {//测试

public static void main(String[] args) {

BankAccount c1=new BankAccount(40000,40000); c1.chaxun(40000,20000); c1.set(20000);

System.out.println(\利率为\ c1.qu(10000);} }

(5)public class Student { String name; int age;

float average,chainese; float math,Enghish;

public Student(String name,int age) {this.name=name;this.age=age;

System.out.println(name+\岁\ public void set(float chinese,float math,float Enghish) {average= (chinese+math+Enghish)/3;} public float get()

{return average;} }

class Undergraduate extends Student// Student继承Undergraduate {public Undergraduate(String name,int age){ super(name,age); }

20

public void hege(float average){ this.average=average; if(average>=60)

System.out.println(\本科生成绩合格\

else System.out.println(\本科生成绩不合格\

class Graduate extends Student// Student继承Graduate {public Graduate(String name,int age){ super(name,age);//调用 }

public void hege(float average){ this.average=average; if(average>=80)

System.out.println(\研究生生成绩合格\

else System.out.println(\研究生成绩不合格\ }

public class StudentDemo {//测试

public static void main(String[] args) {

Undergraduate c1=new Undergraduate(\小明 \ System.out.println(\本科生三门成绩分别为:\ c1.set(65,75,60);

System.out.println(\本科生平均分=\ c1.hege(c1.get());

System.out.println();

Graduate c2=new Graduate(\小红 \

System.out.println(\研究生生三门成绩分别为\

c2.set(80,86,79);

System.out.println(\研究生生平均分=\ c2.hege(c2.get()); }

(6) public abstract class ClosedFigure {//定义抽象类 String shape;

public ClosedFigure(String newShape) {this.shape=newShape;}

public abstract double perimeter();//定义抽象类,里面不能写方法 public abstract double area(); }

public class Triangle extends ClosedFigure {// ClosedFigure继承Triangle double a,b,c;

public Triangle(String newShape,double a,double b,double c) {super(\ this.a=a; this.b=b;

21

this.c=c;}

public double perimeter() {return a+b+c;} public double area() {double s;

s=(a+b+c)/2;

return Math.sqrt(s*(s-a)*(s-b)*(s-c));} public String toString()

{return (\三角形三边长:\周长:\面积:\public class Test {

public static void main(String[] args) {

Triangle c1=new Triangle(\三角形\ c1.perimeter(); c1.area();

System.out.println(c1.toString());} } }

(7)public abstract class Employee { private String firstName; private String lastName;

public Employee(String first,String last) {firstName=first;

lastName=last; } public String getEmployeeName() {return firstName;} public String getLastName() { return lastName;} public String toString()

{return firstName+lastName;} public abstract String earnings(); }

public final class Boss extends Employee{ double salary;

public Boss(String first, String last, double salary) { super(first, last); this.salary = salary;} public String earnings() {return (salary+\ }

public final class CommissionWorker extends Employee { double salary;

22

double sale; double price;

public CommissionWorker(String first, String last, double salary, double sale,double price) { super(first, last); this.salary = salary; this.sale = sale; this.price = price; }

public String earnings()

{return (salary+sale*price+\ }

public final class PieceWorker extends Employee{ double number; double price;

public PieceWorker(String first, String last, double number,double price) {

super(first, last); this.number = number; this.price=price; }

public String earnings()

{return (number*price+\

}

public final class HourlyWorker extends Employee {double time; double money; public HourlyWorker(String first, String last, double time, double money) {

super(first, last); this.time = time; this.money = money; }

public String earnings() { return (time*money+\}

public class Test {

public static void main(String[] args) { Employee c1=new Boss(\张\三\

System.out.println(\张三月工资:\ Employee c2=new CommissionWorker(\李\四\ System.out.println(\李四月工资:\

23

Employee c3=new PieceWorker(\王\五\

System.out.println(\王五月工资:\ Employee c4=new HourlyWorker(\刘\三\

System.out.println(\刘三月工资:\} }

(8)public class Circle { String shape; double r;

double height; double pi;

public Circle(String shape,double r,double height,double pi) {this.shape=shape; this.height=height; this.r=r; this.pi=pi;} }

public interface Volume {

public abstract double area();

public abstract double NewVolume(); }

public class Yuanzhu extends Circle implements Volume {

public Yuanzhu(String shape, double r, double height, double pi) { super(shape, r, height, pi); } public double area() { return pi*r*r;} public double NewVolume() {return area()*height;} }

public class Yuanzhui extends Yuanzhu implements Volume {

public Yuanzhui(String shape, double r, double height, double pi) { super(shape, r, height, pi);

// TODO Auto-generated constructor stub }

double s;

public double area()

{s=Math.sqrt(height*height+r*r); return pi*r*s+pi*r*r;} public double NewVolum()

{return 1.0/3*pi*r*pi*r*height;} }

public class Test {

public static void main(String[] args) { Yuanzhu c1=new Yuanzhu(\圆柱\

24

Yuanzhui c2=new Yuanzhui(\圆锥\ System.out.println(\圆柱表面积:\ System.out.println(\圆柱体积:\ System.out.println(\圆锥表面积:\ System.out.println(\圆锥体积:\}

(9) public interface CanFly {//定义接口CanFly public void fly(); }

public class Plane implements CanFly{//使用接口 @Override

public void fly() {

// TODO Auto-generated method stub

System.out.println(\飞机借助螺旋桨飞上天空\ } }

public class Bird implements CanFly{ @Override

public void fly() {

// TODO Auto-generated method stub

System.out.println(\小鸟 借助翅膀飞上天空\ } }

public class Test {

static void makeFly(CanFly obj){ obj.fly(); }

public static void main(String[] args) { // TODO Auto-generated method stub CanFly p =new Plane(); makeFly(p);

CanFly b =new Bird(); makeFly(b); } }

(10) import java.io.*; public class Ex1 {

public static void main(String args[ ]) {

try{

BufferedReader strin=new BufferedReader(

new InputStreamReader(System.in));//建立输入流缓冲区 System.out.print(\请输入除数:\

String cl=strin.readLine();//键盘输入

25

int a=Integer .parseInt(cl);

System .out .print(\请输入被除数:\ cl=strin .readLine();

int b=Integer .parseInt(cl); int c=b/a;

System .out .println(\商为:\ }

//捕获与I/O有关的异常(空白处补全捕获语句) catch(IOException e)

{System.out.println(\输入输出异常\ //捕获数值转化时的异常,如不能将字符转化成数值 catch(NumberFormatException e)

{System.out.println(\数值格式异常,重新输入\ }

//捕获除数为0的异常

catch(ArithmeticException e)

{System.out.println( \除数为0,重新输入\ } } (11)(1)MyException类: package exp2_11;

public class MyException extends Exception{ MyException (String msg){ super(msg); } }

(2)Div主类: package exp2_11; import java.io.*; public class Div {

public static void main(String args[]) throws MyException{ try{

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print(\请输入实数除法运算的被除数:\ String str = in.readLine();

double a = Double.parseDouble(str); System.out.print(\请输入除数:\ str = in.readLine();

double b = Double.parseDouble(str);

System.out.println(\商结果:\ }

catch(ArithmeticException e1){

System.out.println(\商结果:Infinity\

26

System.out.println(\商结果:NaN\ }

catch(NumberFormatException e2){

System.out.println(\异常:字符串不能转换成整数!\ }

catch(IOException e3){

System.out.println(\异常:IO异常\ }

finally{

System.out.println(\程序结束!\ } }

static double division(double a,double b)throws MyException{ if(a==100 && (b==4 || b==13))

throw new MyException(\不符规范\ else return (a/b); } }

四、实验结果与分析(程序运行结果及其分析)

(1)

去掉Man类的public修饰, 程序运行不出来,提示缺少Man的公开方法。 (2)

(3)

(4)

27

(5)

(6)

(7)

(8)

(9)

(10)

28

(11)

五、实验体会(遇到问题及解决办法,编程后的心得体会)

学习程序设计的基本目的就是培养描述实际问题的程序化解决方案的关键技能Java面向对象程序设计是一门实践性比较强的课程在实际中我们必须把理论和实践结合起来。在实验中我们对照课本的知识然后进行实际的操作而后发现实际的运用比课本提到的要多很多理论总是来源于实践我们必须在现有的理论的基础上进行有效地实践。而这次实验也让我看到了现在学习的一个很大弱点就是实践的实践往往很少。在现实社会中我们必须懂得实际的操作才能更好的服务于社会。所以我必须在以后的学习中多动手多实际操作争取能在实践中找到属于自己新的感悟,终于在学习Java时达到了事半功倍的效果。

29

实验项目名称: 图形用户界面 实验学时: 6 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.5.9~17.5.23 实验成绩: 批改教师: 刘晶 批改时间:

30

实验3 图形用户界面

一、实验目的和要求

(1)掌握Swing组件的使用方法;

(2)熟练掌握Swing中常用布局管理器的使用方法; (3)掌握用户界面动作与事件的处理程序的编写方法; (4)熟练掌握构造用户界面的方法和常见界面元素的使用; (5)熟练掌握Java绘图的主要方法。

(6)调试程序要记录调试过程中出现的问题及解决办法;

(7)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;

(8) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。

三、实验过程

1. 计算器设计

2. 整数进制转换

将一个十进制整数分别转换成二进制、八进制和十六进制整数。

3. 模拟裁判评分。

设计如图所示图形界面,显示n个裁判的评分,根据制定规则计算出最后得分。要求:图形界面采用表格显示裁判评分,随裁判人数变化而变化;指定分数范围,若超出,则异常处理;

31

得分规则有指定接口约定,由多个接口对象给出多种得分规则,如求平均数值,或去掉一个最高分和一个最低分后,再求平均值。

4. 编译运行下例,然后修改程序,当使用鼠标单击后在另一位置重新绘制月亮。 【例】 在Applet中画月亮。 import java.awt.*;

import java.applet.Applet;

public class MoonApplet extends Applet {

public void paint(Graphics g) //在Applet上绘图 {

g.setColor(Color.red);

g.drawString(\

int x=0,y=0; //圆外切矩形左上角坐标 x = this.getWidth() /4; y = this.getHeight() /4;

int diameter = Math.min(this.getWidth()/2, this.getHeight()/2); //圆的直径

g.setColor(Color.yellow);

g.fillOval(x,y,diameter,diameter); //画圆

g.setColor(this.getBackground()); //设置为背景色 g.fillOval(x-20,y-20,diameter,diameter); //画圆 } }

5.根据阿基米德螺线的极坐标方程:r=aθ画出相应图形。

要求:

(1)注意选用适当的布局管理器设计图形用户界面,比较它们的布局情况;

(2)养成良好的编程习惯,严格按照命名规则为包、类及类成员命名,将每个程序打包,包的命名方式如three.num1表示实验三的第一题; (3)学会使用Eclipse的各种调试方法;

(4)学会查阅Java API文档,如查找事件类的处理里方法。

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。)

1.import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.*; import javax.swing.*;

32

public class Calulator implements ActionListener { JTextField t1; JPanel p1; JFrame f;

static int count=1; static float value=0; int p2=0; String p; public Calulator()

{f=new JFrame(\ f.setSize(400,200); p1=new JPanel();

t1=new JTextField(30);

t1.setHorizontalAlignment(JTextField.RIGHT); p1.setLayout(new GridLayout(5,4)); f.add(t1); String str[]=

{\开根\清零\负\正\ for(int i=0;i<20;i++)

{JButton b=new JButton(str[i]); p1.add(b);

b.addActionListener(this);}

f.add(t1,BorderLayout.CENTER); f.add(p1,BorderLayout.SOUTH);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true);}

public void actionPerformed(ActionEvent e){ String c = e.getActionCommand();

if(c==\=\

{if(p2==0) {t1.setText(c);p2++;}

else {t1.setText(t1.getText()+c); p2++;}}

else if(p==\清零\else {count++; p2=0;

if(count==2 ) {p=c;value=Float.parseFloat(t1.getText());} if(c==\if(p==\开根\

{value=(float)Math.sqrt(Float.parseFloat(t1.getText())); t1.setText(String.valueOf(value));count-=2; } else

if(p==\ else

if(p==\

33

else

if( p==\ else

if(p==\

else if (p==”正”)

{value=Math.abs(Float.parseFloat(t1.getText())); t1.setText(String.valueOf(value)); count-=2;}

else if(p==\负\ t1.setText(String.valueOf(value));count-=2;} t1.setText(String.valueOf(value));value=0;}} }

public static void main(String[] args) { new Calulator(); }}

2.import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class ZhuanH extends JFrame implements ActionListener{ TextField t1,t2,t3,t4; public ZhuanH()

{super(\十进制整数转换\

this.setBackground(Color.BLUE); t1=new TextField(5); t2=new TextField(5); t3=new TextField(5); t4=new TextField(5); t1.setText(null);

this.setSize(400,200);

this.setLayout(new GridLayout(4,2)); this.add(new Label(\十进制\

this.add(t1);t1.addActionListener(this); this.add(new Label(\二进制\this.add(new Label(\八进制\this.add(new Label(\十六进制\this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); }

public void actionPerformed(ActionEvent e){ String c = t1.getText();

t2.setText(Integer.toBinaryString(Integer.parseInt(c))); t3.setText(Integer.toOctalString(Integer.parseInt(c)));

34

t4.setText(Integer.toHexString(Integer.parseInt(c))); }

public static void main(String[] args) { new ZhuanH(); }}

3.import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class PingFen extends JFrame implements ActionListener{ JPanel p,p1; JTextField t;

JTextField t1[]=new JTextField[10]; JButton b; float s=0,k; int t2,t3;

public PingFen() {

super(\模拟裁判评分\ this.setSize(300,120);

p1=new JPanel(new GridLayout(2,5)); this.add(p1,\

p=new JPanel(new FlowLayout(FlowLayout.RIGHT)); this.add(p,\ b=new JButton(\平均分\ t=new JTextField(10); p.add(b);p.add(t); for(int i=0;i<10;i++) {

t1[i]=new JTextField(6); t1[i].setText(null);

p1.add(t1[i]); }

b.addActionListener(this);

this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true);}

public void actionPerformed(ActionEvent e) {float max,min;

for(int i=0;i<10;i++) { try{

if(Float.parseFloat(t1[i].getText())>10.0) throw new Exception(); else continue;} catch(Exception ev)

{JOptionPane.showMessageDialog(this,t1[i].getText()+\超出范围\

35

请重新输入\

t1[i].setText(null);} }

max=Float.parseFloat(String.valueOf(t1[0].getText())); min=Float.parseFloat(String.valueOf(t1[0].getText())); for(int i=1;i<10;i++) {

if((k=Float.parseFloat(String.valueOf(t1[i].getText())))>max){max=k;t2=i;} else if

((k=Float.parseFloat(String.valueOf(t1[i].getText())))

for(int i=0;i<10;i++) {

if(t2!=i&&i!=t3)

s+=Float.parseFloat(String.valueOf(t1[i].getText()));} t.setText(s/10.0+\

public static void main(String[] args) { new PingFen();}} 4. import java.awt.*;

import java.applet.Applet; import java.awt.event.*;

public class MoonApplet extends Applet implements MouseListener {

int x,y;

public void init(){

x=this.getWidth()/4; y=this.getHeight()/4; addMouseListener(this); }

public void paint(Graphics g) //在Applet上绘图 {

g.setColor(Color.red);

g.drawString(\ int diameter = Math.min(this.getWidth()/2, this.getHeight()/2); //圆的直径

g.setColor(Color.yellow);

g.fillOval(x,y,diameter,diameter); //画圆

g.setColor(this.getBackground()); //设置为背景色 g.fillOval(x-20,y-20,diameter,diameter); //画圆 }

public void mouseClicked(MouseEvent e){

36

x=e.getX(); y=e.getY(); repaint(); }

5. package package2; import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class LuoXuan extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;

private LuoXuanCanvas canvas; //自定义画布组件 public LuoXuan()

{super(\阿基米德螺线\

Dimension dim=getToolkit().getScreenSize();

this.setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2); JPanel p=new JPanel(); this.add(p,\

JButton b=new JButton(\选择颜色\p.add(b);

b.addActionListener(this);

this.canvas=new LuoXuanCanvas();

this.getContentPane().add(this.canvas, \this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true);}

public void actionPerformed(ActionEvent e)

{Color c=JColorChooser.showDialog(this, \选择颜色\ this.canvas.setColor(c); this.canvas.repaint();}

public static void main(String[] args) { new LuoXuan();} }

class LuoXuanCanvas extends Canvas {private Color color;

public void LuoXuan(Color color) {this.setColor(color);}

public void setColor(Color color){this.color=color;} public void paint(Graphics g) {int x0=this.getWidth()/2; int y0 = this.getHeight()/2; g.setColor(this.color);

g.drawLine(x0, 0, x0, y0*2); g.drawLine(0, y0, x0*2, y0);

37

for(int i=0;i<4000;i++)

{double angle=i*Math.PI/512; double radius=angle*0.5;

int x=(int)Math.round(radius*angle*Math.cos(angle)); int y=(int)Math.round(radius*angle*Math.sin(angle)); g.drawOval(x0+x, y0+y, 1, 1);} }}

四、实验结果与分析(程序运行结果及其分析)

(分析每题采用的布局管理器、事件处理类和主要功能实现方法) 1.

2.

3.

4.

38

本文来源:https://www.bwwdw.com/article/tdv3.html

Top