JAVA面向对象技术及应用实验指导修订.doc_第1页
JAVA面向对象技术及应用实验指导修订.doc_第2页
JAVA面向对象技术及应用实验指导修订.doc_第3页
JAVA面向对象技术及应用实验指导修订.doc_第4页
JAVA面向对象技术及应用实验指导修订.doc_第5页
已阅读5页,还剩20页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Java程序设计实验指导书 目 录实验2 Java 基本语法练习一、实验目的1 了解 Java 的数据类型2 掌握各种变量的声明方式。3 理解运算符的优先级。4 掌握 Java 基本数据类型、运算符与表达式、数组的使用方法。5 理解 Java 程序语法结构,掌握顺序结构、选择结构和循环结构语法的程序设计方法。6 通过以上内容,掌握 Java 语言的编程规则。二、实验要求1. 编写一个声明 Java 不同数据类型变量的程序。2. 编写一个使用运算符、表达式、变量的程序。3. 编写一个使用 Java 数组的的程序。4. 编写表达式语句、复合语句的程序。5. 编写使用不同选择结构的程序。6. 编写使用不同循环结构结构的程序。三、实验内容(一)声明不同数据类型的变量1编写声明不同数据类型变量的程序文件 LX2_1.java,源代码如下。public class LX2_1 public static void main(String args) byte b=0x55; short s=0x55ff; int i=1000000; long l=0xffffL; char c=a; float f=0.23F;double d=0.7E-3;boolean B=true;String S=这是字符串类数据类型; System.out.println(字节型变量 b = +b); System.out.println(短整型变量 s = +s); System.out.println(整型变量 i = +i); System.out.println(长整型变量 l = +l); System.out.println(字符型变量 c = +c); System.out.println(浮点型变量 f = +f); System.out.println(双精度变量 d = +d); System.out.println(布尔型变量 B = +B); System.out.println(字符串类对象 S = +S);2编译并运行该程序,结果如图 2.1 所示。图 2.1(二)了解变量的使用范围1建立 LX2_2.java 文件,通过本程序了解变量的使用范围,源代码如下。public class LX2_2 static int i=10;public static void main(String args) int k=10; System.out.println(i=+i); System.out.println(k=+k);System.out.println(i=+i); System.out.println(k=+k);/编译时将出错,已出 k 的使用范围2编译 LX2_2.java此时会出现错误提示如图 2.2 所示。因为变量 k 在方法块中声明,在方法块之外它是不存在的, 所以编译时会出错。图 2.23修改上面的程序。4成功运行该程序。思考:LX2_2.java 程序说明了什么问题?(三)使用关系运算符和逻辑运算符1建立使用关系运算符和逻辑运算符的程序文件,源代码如下。class LX2_3 public static void main(String args) int a=25, b=20, e=3, f=0;boolean d=ab;System.out.println(a=25,b=20,e=3,f=0); System.out.println(因为关系表达式 a5)System.out.println(因为 e 非 0 且 a/e 为 8 大于 5,所以输出a/e +a/e);if (f!=0 & a/f5) System.out.println(a/f = +a/f); elseSystem.out.println(因为 f 值为 0,所以输出f = +f);2编译并运行该程序,结果如图 2.3 所示。图 2.3(四)使用数组1建立使用数组的程序,本程序建立了一个长度为 5 的 1 维数组,一个长度为 12 的 2 维数组, 源代码如下。public class LX2_4 public static void main(String args) int a=new int5;int arr1=new int34;a0=10; a1=10+a0; a2=30; a3=40;a4= a1+ a2;arr100=0; arr101=1; arr102=2; arr110=3; arr111=4; arr112=5; arr120=6; arr121=7; arr122=8;System.out.println(a+0+ = +a0); System.out.println(a+1+ = +a1); System.out.println(a+2+ = +a2); System.out.println(a+3+ = +a3); System.out.println(a+4+ = +a4);System.out.println(arr1(+0+,+0+) = +arr100);System.out.println(arr1(+0+,+1+) = +arr101); System.out.println(arr1(+0+,+2+) = +arr102); System.out.println(arr1(+1+,+0+) = +arr110); System.out.println(arr1(+1+,+1+) = +arr111); System.out.println(arr1(+1+,+2+) = +arr112);2编译并运行程序,结果如图 2.4 所示。图 2.4(五)使用表达式语句与复合语句1 建立包含表达式语句程序,源代码如下。class LX2_5public static void main(String args) int k, i=3, j=4;k=20*8/4+i+j*i; System.out.println(表达式(20*8/4+i+j*i)+k);2 建立包含复合语句程序,源代码如下。class LX2_6public static void main(String args) int k, i=3, j=4;k=i+j;System.out.println(在复合块外的输出k=+k);float f; f=j+4.5F; i+;System.out.println(在复合块内的输出f=+f);System.out.println(在复合块内的输出k=+k);System.out.println(在复合块外的输出i=+i);3 编译并运行上述两个源程序,结果如图 2.5、2.6 所示。图 2.5图 2.64 将变量 i 在块内定义会怎样?改变其他变量的位置看看会发生什么变化。 思考:指出程序的复合结构以及变量的使用范围。(六)使用选择语句1使用 if.else 语句(1)程序功能:使用 if.else 语句构造多分支,判断某一年是否为闰年。闰年的条件是符合下 面二者之一:能被 4 整除,但不能被 100 整除;能被 4 整除,又能被 100 整除。(2)编写源程序文件,代码如下。public class LX2_7 public static void main(String args) boolean leap;int year=2005;if (year%4=0 & year%100!=0) | (year%400=0)/ 方法 1System.out.println(year+ 年是闰年);elseSystem.out.println(year+ 年不是闰年);year=2008;/ 方法 2 if (year%4!=0) leap=false;else if (year%100!=0)leap=true;else if (year%400!=0)leap=false; else leap=true;if (leap=true)System.out.println(year+ 年是闰年);elseSystem.out.println(year+ 年不是闰年);year=2050;/ 方法 3if (year%4=0) if (year%100=0) if (year%400=0) leap=true;elseleap=false;else leap=false;else leap=false;if (leap=true)System.out.println(year+ 年是闰年);elseSystem.out.println(year+ 年不是闰年);(3)编译运行程序,其结果如图 2.7 所示。图 2.7思考:本程序中有几个选择语句,哪些具有嵌套关系?2使用 switch 语句(1)程序功能:在不同温度时显示不同的解释说明。(2)程序源代码如下。class LX2_8public static void main(String args) int c=38;switch (c10?1:c25?2:c35?3:4) case 1:System.out.println( +c+ 有点冷。要多穿衣服。);case 2:System.out.println( +c+ 正合适。出去玩吧。);case 3:System.out.println( +c+ 有点热。);default:System.out.println( +c+ 太热了!开空调。);(3)编译运行程序,其结果如图 2.8 所示。图 2.8(七)使用循环语句1 for 循环语句练习(1) 程序功能:按 5 度的增量打印出一个从摄氏温度到华氏温度的转换表。(2) 程序源代码如下。class LX2_9public static void main (String args) int h,c;System.out.println(摄氏温度华氏温度);for (c=0; c=40; c+=5) h=c*9/5+32;System.out.println(+c+h);(3)编译并运行程序,其结果如图 2.9 所示。图 2.92 while 循环语句练习(1)程序功能:运行程序后从键盘输入数字 1/2/3 后,可显示抽奖得到的奖品;如果输入其它数 字或字符显示“没有奖品给你!”。(2)程序源代码如下。 import java.io.*; class LX2_10 public static void main(String args) throws IOException char ch;System.out.println(按 1/2/3 数字键可得大奖!); System.out.println(按空格键后回车可退出循环操作.); while (ch=(char)System.in.read()!= ) System.in.skip(2);/ 跳过回车键switch (ch) case 1: System.out.println(恭喜你得大奖,一辆汽车!); break;case 2:System.out.println(不错呀,你得到一台笔记本电脑!);break;case 3: System.out.println(没有白来,你得到一台冰箱!); break;default:System.out.println(真不幸,你没有奖品!下次再来吧。);(3)编译源程序。(4)在命令提示符窗口运行程序,然后分别按 1、2、3、r 结果如图 2.10 所示。图 2.103dowhile 循环语句练习(1)程序功能:求 12+100 之和,并将求和表达式与所求的和显示出来。(2)程序源代码如下。class LX2_11 public static void main(String args) int n=1, sum=0;do sum+=n+; while (n=100); System.out.println(1+2.+100 =+sum);(3)编译并运行程序,结果如图 2.11 所示。图 2.114多重循环练习(1)输出九九乘法表的程序,源代码如下。public class LX2_12public static void main(String args)int i,j,n=9;System.out.print(*|);for (i=1;i=n;i+) System.out.print(+i);System.out.print(n-|);for (i=1;i=n;i+) System.out.print(-); System.out.println();for (i=1;i=n;i+)System.out.print(+i+|); for (j=1;j=i;j+) System.out.print(+i*j); System.out.println();(2)编译并运行程序,结果如图 2.12 所示。图 2.12四、练习题1分析下面的程序,说出下面的程序为什么是死循环?class Sum public static void main(String args) int i=1,n=10,s=0;while (i=n)s = s + i; System.out.println(s=+s);2分析下面源程序的结构,写出运行结果。class CircleArea final static double PI=3.14159;public static void main(String args) double r1=8.0, r2=5.0; System.out.println(半径为+r1+的圆面积+area(r1); System.out.println(半径为+r2+的圆面积+area(r2);static double area(double r) return (PI*r*r);2编写程序,根据考试成绩的等级打印出百分制分数段。设 A 为 90 分以上、B 为 80 分以上、C为 70 分以上、D 为 60 分以上、E 为 59 分以下。要求在程序中使用开关语句。3完整下面的程序,利用 break 语句和带标号的 break 语句分别退出一重循环和二重循环。for (i=0; i10; i+)int j=i*10while(j100)if (j=10) break; j=j+5;实验3 面向对象程序设计基本操作一、实验目的通过编程和上机实验理解 Java 语言是如何体现面向对象编程基本思想,了解类的封装方法,以及 如何创建类和对象,了解成员变量和成员方法的特性,掌握 OOP 方式进行程序设计的方法,了解类的 继承性和多态性的作用。二、实验要求1. 编写一个体现面向对象思想的程序。2. 编写一个创建对象和使用对象的方法的程序。3. 编写不同成员变量修饰方法的程序。4. 编写不同成员方法修饰方法的程序。5. 编写体现类的继承性(成员变量、成员方法、成员变量隐藏)的程序。6. 编写体现类的多态性(成员方法重载、构造方法重载)的程序。三、实验内容Simple Motors Ltd is a small business enterprise that is currently overwhelmed by the processing of employees expenses and reporting requirements set up by various external organizations. The out-of-pocket expenses must be paid back to the employee at the regular intervals. Once a year total expenses and tax paid during that period must be summarised and incorporated into the reports prepared for ATO. Some of the expenses contribute towards the research and development targets set by Federal Government. Those targets are calculated using RD credit points. You have been asked to develop the program that is going to help the company with the processing of employees expenses. The initial class structure for this program is shown below. The program is to be developed in stages and every stage must be finished with a running program.Stage 1You will implement two classes: Expense and ResearchExpense. Expense is an abstract class that will be located on the top of the expense class hierarchy. The following table summarises its methods and attributes. You can relax the information hiding rules and use protected if you wish.Class: Expense (abstract) DetailsCommentsisPaidBoolean, indicate whether an employee has been reimbursed for the expense.dateString is sufficient here; (get/set)descriptionString; (get/set)Expense()Default constructorExpense(date,description)Constructor, two parametersisPaid():booleanReturns the value of isPaidisPaid(isPaid:boolean) :voidSets the value of isPaid to true or falsetoString():StringgetTotal():doubleAbstract; returns the total monetary value of the expense including tax paid.getTax():doubleAbstract; returns the tax paidgetRDPoints():intAbstract; returns the research and development points accumulated via the expenseClass: ResearchExpense (inherits from Expense)DetailsCommentscostTotal cost of the expense (get/set)taxTax paid (get/set)RD_COEFFConstant, value = 2, coefficient used to calculate RD points.ResearchExpense()Default constructorResearchExpense(date, description, cost, tax)Constructor, all needed parameterstoString():String getTotal():doubleReturns the total monetary value of the expense including tax paid.getTax():doublereturns the tax paidgetRDPoints():intReturns research and development points gain for this expense, multiply the total expense before tax (truncated to the whole dollar) by RD_COEFF.Build the class diagram for the above classes using Rational Rose (other programs are not accepted). Save it as javaAssign.mdl. Implement the classes in JAVA and built a program to test them -Stage1Tst.java. The program should create two different ResearchExpense objects and call all relevant methods non-interactively (no user intervention). Deliverables stage 1: Stage1Tst.java, ResearchExpense.java, Expense.java, javaAssign.mdl.Stage 2In a spirit of OOP with polymorphism we will leave the Expense class hierarchy for the moment and now you are to implement the class Employee. Every expense is recorded against a particular employee. The new class Employee will be working as a container class for Expense.Class: EmployeeDetailsCommentsnameString to uniquely identify the employee (set/get)expensesArrayList, contains all expenses registered against a particular employee. (Please fill free to use a Vector or an Array if you prefer)Employee()Default constructorEmployee(name)Constructor, all needed parameterstoString():String Returns the string that contains the name of the employee plus all expenses (call toString() method for the Expense class). Every expense is listed on a new line and is indented by one tab stop.addExpense(e:Expense)getExpense(i:int):ExpenseReturns the Expense object indexed by i.noOfExpenses:intTotal number of expenses listed for the employeeiterator():IteratorReturns an iterator to provide an elegant access to the expenses collection (method is optional; you can use getExpense(i) instead, not applicable if you use arrays) reimburse():doubleReturns the total to be paid to the employee and set all expenses used in a process as paid.getTotal():doubleReturns the total value of the expenses including tax paid regardless if they were reimbursed or not.getTax():doublereturns the total value of tax paid regardless if the expenses were reimbursed or notgetRDPoints():intReturns to total number of RD points.Please note that for this assignment there is no need to implement methods to delete or modify the objects once they were added to the container (a significant simplification).In OOP, when domain classes are implemented, no assumption should be made about the user interface that later will be used to create objects. That led to the idea of object factories, sperate classes that are used to create objects. Their methods are static and usually there is at least one method per object type to be created. In the assignment, you will be creating expenses interactively, thus the class ExpenseFactory. Class: ExpenseFactory DetailsCommentskbReadResearchExpense(): ResearchExpenseStatic, returns new object of the type ResearchExpense, ask the user for all relevant details using the method of your choice (for example EasyIn), create a new ResearchExpense object and return it.Update your class diagram. Implement Employee.java and ExpenseFactory.java. Create new testing program Stage2Tst.java that creates an employee, 5 expenses (one entered interactively by calling kbReadResearchExpense() from ExpenseFactory ) and tests all relevant methods.Deliverables stage 2: Stage2Tst.java, Employee.java, ExpenseFactory.java, ResearchExpense.java, Expense.java, javaAssign.mdl.Stage 3 Now you will implement another expense type class CarExpense. Car expense is an example of a travel expense. Subsequently two new classes must be implemented and the class ExpenseFactory updated.Class: TravelExpense (abstract) DetailsCommentsdestinationString; (get/set)TravelExpense()Default constructorTravelExpense()Constructor, all needed parameterstoString():StringgetRDPoints():intReturns 0, travel expenses are not contributing to research points.Class: CarExpense (inherits from Expense)DetailsCommentskm:doubleKilometres made (get/set)costPerKm:doublestatic (get/set)CarExpense ()Default constructorCarExpense()Constructor, all needed parameterstoString():String getTotal():doubleReturns (km*costPerKm)getTax()Returns 0Update class: ExpenseFactory DetailsCommentskbReadResearchExpense(): ResearchExpenseAs abovekbReadCarExpense(): CarExpenseAs above but for a CarExpense object createExpense():ExpenseAsk the user for the type of expense to be created and then calls the appropriate “kb” method. The place where switch-type logic (switch(expense type) is implemented. Now the advantages of using the factory base class can be appreciated. To add new expense type, only the factory class is to be modified by adding another kbReadClassName() method and one more case option to the createExpense() method. Update your class diagram. Create/modify relevant java files. Update Stage2Tsts.java by creating 3 additional car expenses (one must be interactive via createExpense() ). Set the value of costPerKm to $0.50. Save it as Stage3Tst.java . The rest of your program should run with no changes.Deliverables stage 3: Stage3Tst.java, Employee.java, TravelExpense.java, ExpenseFactory.java, CarExpense.java, ResearchExpense.java, Expense.java, javaAssign.mdl.Stage 4The company has two employees at the moment “Alice” and “Tom”. New class will be created that will hold all Employee type objects. Class: CompanyDetailsCommentsnameString, company name (set/get)employeesArrayList, contains all employees. (Please feel free to use a Vector or an Array if you prefer)Company()Constructor, all needed parameterstoString():String Calls toString method for every individual employee and returns the result.addEmployee(e:Employee)search(name:String) :EmployeeSearches for the employee identified by the name. Returns null or the employee object.getEmployee(i:int) :EmployeeReturns the Employee object indexed by i.noOfEmployees():intTotal number of employeesiterator():IteratorReturns an iterator to the employee collection (method is optional) addExpense(name:String e:Expense):booleanAdds expense to the employee identified by the name. Calls the search method first. Returns true if the operation succeeded.reimburseEmployees() :voidCalls reimburse method for every employee. It displays the employee name, total to be reimbursed for an employee, plus the grand total at the end of the employee listing. totalExpenses():doubleReturns the total value of all expenses. totalTax():doubleAs above but for the taxtotalRDPoints():intAs above but for RD points.Update your class diagram. Create/modify relevant java files. In Stage4Tsts.java create two employees and add a series of expenses for them. Then test every method one by one. Deliverables stage 4: Stage4Tst.java, Company.java, Employee.java, TravelExpense.java, ExpenseFactory.java, CarExpense.java, ResearchExpense.java, Expense.java, javaAssign.mdl.Stage 5Now you are ready to build a user interface for your program. The following applies to a text based menu. You are free to implement other interface as long as the functionality of the program is preserved. Build a menu with the following options:Add expenseReimburse EmployeesDisplay TotalsDisplay New ExpensesMemory DumpQuitClass: MyUI DetailsCommentscompanyCompanymyUI()Default constructor; builds a new company object with 2 employees and 10 expenses for testing purposes. run()Displays the above menu and processes the options until user want to quitaddExpense():voidImplements option 1. It asks user for the employee name, calls createExpense() from ExpenseFactory and addExpense() from Company.reimburse()calls reimburseEmployees() from CompanydisplayTotals()Display total expense, total tax, and total RD points by calling appropriate functions from Company.displayNewExpenses()Display the details about the unpaid expenses (more difficul

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论