版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Java实验二CXY,BIT实验1.1Pi can be calculated using the following sum, which is an approximation to Pi/4 : PiSum = 1 - 1/3 + 1/5 - 1/7 + . + (-1)n / (2*n + 1) 1) Write two methods that return PiSum for a specified value of n, one method using recursion and the other using iteration to do the sum. Hint: in
2、stead of calculating (-1)n, you can check whether the nth term is negative by checking whether n%2 (i.e. n modulo 2) is 1. Assume that the methods are always called with a non-negative value of n, so you don't need to worry about dealing with invalid parameter values. 2) Show the additional code
3、 you would add to the above methods to throw an exception if n is less than zero (you don't need to rewrite the whole method). The exception handler should generate an error message saying that the number of terms in the sum must not be negative. Write a code fragment (i.e. it doesn't need t
4、o be a complete method) that invokes one of the methods for calculating Pi and prints out the result if the method returns correctly, or else catches an exception and prints out the error message returned. 3) When calculating Pi using the given formula, suppose that instead of passing a parameter sp
5、ecifying the number of terms n in the sum, we instead want to pass a parameter that specifies a precision value. The sum should terminate at the first value n for which the absolute value of the nth term in the sum, i.e. 1/(2*n+1) is less than the specified precision. Show how this can be implemente
6、d using a do loop.import java.io.*;class myexception extends Exceptionprivate int a; /自定义exceptionmyexception(int a)this.a=a;public String getmyexception()return "Exception:the number of terms in the sum must not be negative!"public class calculate double pisum=0.0,pisum2=0.0;void calculat
7、e() pisum=0.0; /初始化void caln(int n) pisum=0.0;for(double i=0;i<=n;i+)if(i%2=1)pisum-=1.0/(2*i+1.0);elsepisum+=1.0/(2*i+1.0);("PiSum="+pisum);double digui(int n)double z=1.0/(2*n+1.0);if(n=0) return 1.00;else if(n%2=0) return digui(n-1)+z; else return digui(n-1)-z; void calprecision(doub
8、le n) pisum=0.0;double i=0.0;doif(i%2=1)pisum-=1.0/(2*i+1.0);elsepisum+=1.0/(2*i+1.0);i+=1;while(1.0/(2*i+1.0)>=n);("PiSum="+pisum); static void test1(int a) throws myexception if(a<0) throw new myexception(a); /若a<o则抛出 public static void main(String args) throws IOException Buffe
9、redReader buf; String str; int n; double precision; calculate example=new calculate(); buf= new BufferedReader(new InputStreamReader(System.in); ("in put a Positive integer"); /输入 str=buf.readLine(); n=Integer.parseInt(str); try test1(n); if(n>=0) ("Using Iteration:"); example
10、.caln(n); ("Using Recursion:"); ("PiSum="+example.digui(n); catch(myexception e) ("Caught "+e.getmyexception(); (); ("in put a precision value"); str=buf.readLine(); precision=Double.parseDouble(str); example.calprecision(precision); 设计思路:a. 精度算法按照题目要求写,当1/(2*
11、n+1) 小于精度的时候即可停止。b. 自定义exception,规定当输入的n<0的时候报错,若n>=0则分别用迭代、递归方法进行计算,其中递归:当n=0时为最底层,return 1;c. 计算的时候按照n%2的值来确定是加还是减。运行结果:1.1 输入n值大于等于0时 1.2输入n小于0时试验2.2. a) Produce an abstract class to represent a general Shape. It must have the following properties: i) Instance variables to represent the (x,
12、 y) coordinate of the shape. Limit their visibility to the Shape class only. ii) It requires a constructor which initializes the (x, y) coordinate of the shape. Limit the visibility of the constructor to only the Shape class and classes that extend it. iii) Abstract methods to determine the area and
13、 circumference (perimeter) of the Shape are required. Make sure that these methods are visible to everyone. iv) A concrete move method is needed so that the (x, y) coordinate of the Shape can be altered. Users should be able to indicate a relative move (i.e., 3 places left, 4 up) rather than specify
14、 an absolute location. This method should be visible to everyone. v) A print method that displays the (x, y) coordinates of the Shape and provides its area and circumference. This method should be visible to everyone. b) Define 2 classes, Square and Circle, which extend the class Shape above: i) Squ
15、are will require an instance variable to hold the length of the sides, and Circle will require an instance variable to hold the radius. ii) Make sure that the constructors are defined to properly initialize all instance variables. iii) The print method must be overridden so that it displays the leng
16、th of the sides, or radius (as appropriate) in addition to displaying all the information that the print method from the superclass displays. Hint: The area of a circle is given by er2, and the circumference is 2er, where r is the radius of the circle. The value of e should be obtained by using c) W
17、rite an application to test the Shape class that performs the following: i) Declares an array of Shape objects. ii) Initialize the array so that it contains two Square objects of length 1 and 2 whose origin is (0, 0), and two Circle objects whose radius are 3 and 4 whose origin is also (0, 0). iii)
18、Code to iterate over the Shape array and print out information about the shape. abstract class shape private int x,y; protected shape(int a,int b) x=a; y=b; public abstract void area(int b); public abstract void circumference(int a); public void move(int a,int b) ("Coordinate before move:"
19、+"("+x+","+y+")"); x+=a; y+=b; ("Coordinate after move:"+"("+x+","+y+")"); public void print() ("Coordinate:("+x+","+y+")"); class Square extends shapeint lenth;protected Square(int a,int c,int d)supe
20、r(c,d);lenth=a;void area() int s; s=lenth*lenth; ("Area of Square:"+s); void circumference() int l; l=4*lenth; ("Circumference of Square:"+l); public void print() super.print(); ("Lenth of sides:"+lenth); area(); circumference(); class Circle extends shapeint r,x,y;prot
21、ected Circle(int n,int c,int d)super(c,d);r=n;void area()double s; s=()*r*r; ("Area of Circle:"+s); void circumference()double l; l=2*r; ("Circumference of Circle:"+l); public void print() super.print(); ("Nradius:"+r); area(); circumference(); public class test public
22、static void main(String args)Square example1=new Square2;example10=new Square(1,0,0);example11=new Square(2,0,0);Circle example2=new Circle2;example20=new Circle(3,0,0);example21=new Circle(4,0,0);for(int i=0;i<2;i+)("Square "+i+":"); example1i.print(); (); for(int j=0;j<2;
23、j+)("Circle "+j+":"); example2j.print(); ();设计思路:a. 建立抽象类Shape的子类Square和Circle, Shap(int a, int b)构造方法为初始化坐标(a,b),子类Square/Circle(inta,intb,intc)则为(边长/半径,横坐标,纵坐标)。b. 在Shape中声明抽象方法area()和circumference(),在每个子类中重写,分别重写对应的计算方法。c. 每个类以及方法均按照题目要求权限设置,并注意在子类中也要是同样的设置。运行结果:实验2试验3.3编写程序,从
24、命令行参数读取一个字符串,然后 1)检验它是否是回文;2) 显示其中最大连续递增的有序子串。 import java.io.*;public class dealString public static void main(String args) throws IOException byte buffer=new byte200; byte buf=new byte200; int count,bestk=0,k=1; boolean flag=false; ("Please Input a String"); count=(buffer); count-=2; for
25、(int i=0;i<count;i+) if(bufferi!=buffercount-i-1) flag=true; if(count-i<bestk) break; k=1; for(int j=i+1;j<count;j+) if(bufferj>bufferj-1) k+=1; else break; if(k>bestk) bestk=k; System.arraycopy(buffer,i,buf,0,bestk); if(flag) ("This String is Not a Palindrome"); else ("
26、;This String is a Palindrome"); ("The Longest Ascending Subsequence is:"); for(int h=0;h<bestk;h+) (char)bufh); 设计思路:a. 输入流将字符串分成字符数组记录下来。b. 将字符串数组头尾进行比较,若头尾对称相等,则为回文,反之则不是。c. 循环比较,记录当前最长的递增子序列,直到将字符串数组遍历以后,方可得出最长子序列。运行结果:3.1 是回文输入3.2 不是回文输入试验4.4. You are asked to write a student m
27、arks program that reads in a file of student marks, then calculates the mean of these marks and, finally, outputs these values to standard output. Marks are stored in a file called: cs1marks.dat in the format of <student's last name> <mark> , one student per line. For example: Smith
28、85 Jones 72 You are given the class StudentRecord (see attachment), which defines an object that contains a student name and mark. The class has methods for getting the name and mark from the StudentRecord. You are given the incomplete driver class MarksMain (see attachment). This driver creates a n
29、ew MarksFile object and reads the MarksFile via the readFile method (do not worry how the file is read in yet). For this part, the only thing you need to know is that the readFile method returns a Vector of StudentRecord objects. 1) Complete the indicated section of MarksMain, which prints to standa
30、rd out: · the student results stored in the Vector marks, and · the average of the marks. 2) Examine the skeleton of the MarksFile class(see attachment). There are two methods that must be implemented: the constructor MarksFile and the method readFile. 2.1) The MarksFile constructor, takes
31、 a filename as an argument and creates an input character stream to the file. This stream is assigned to the variable fs. Note that the type of fs is not given. What is the correct type for the variable fs? 2.2) The readFile method reads in each line of data from the data file and creates a new Stud
32、entRecord with a name and mark. It then stores this new StudentRecord in the Vector results. When all the values have been read and stored, it returns the Vector results. Complete the missing section to read in the values from the file and store them in results. Marksfile:import java.util.*;import j
33、ava.io.*;public class MarksFile private FileReader fs;public MarksFile(String filename) / creates an input character stream to the file and assign to variable/ fstry fs = new FileReader(filename); catch (Exception e) ("File not found.");public Vector<Object> readFile() String line =
34、new String();/ create a buffered reader so we can read in a lineBufferedReader inFile = new BufferedReader(fs);Vector<Object> stu = new Vector<>();try while (line = inFile.readLine() != null) int posi = line.indexOf("t");/找到空格前边是名字后边是分数String name = line.substring(0, posi - 1);
35、int score = Integer.parseInt(line.substring(posi + 1);stu.add(new StudentRecord(name,score);/变成StudentRecord然后加入到stu中 catch (IOException e) ("IO exception");/ close the filetry inFile.close(); catch (IOException e) ("IO exception");return stu;Marksmain:import ;import ;import java
36、.io.*; class StudentRecord private String studentName;private int mark;public StudentRecord(String name, int value) studentName = name;mark = value;public String getName() return studentName;public int getMark() return mark;public class MarksMain public static void main (String args)final String fil
37、eName = "cs1marks.dat"Vector marks; / marks is a Vector of Mark objectsStudentRecord entry;int averageSum = 0;MarksFile cs1MarksFile = new MarksFile(fileName);/ marks is a Vector of StudentRecord objectsmarks = cs1MarksFile.readFile();for(int i = 0;i < marks.size();+ i)/遍历每一个学生entry = (
38、StudentRecord) marks.elementAt(i);(entry.getName() + "t" + entry.getMark();/输出流中的学生信息averageSum += entry.getMark();("Average" + averageSum / marks.size();/输出平均成绩/ print out each student's mark on a separate line in the/ format: Student Name <tab> mark/ at the end print
39、out on a separate line the average (mean) mark in the/ format: Average: avg mark/FILL IN THE CODE HERE 设计思路:a. 将文件内容存入Vector marks中b. 将空格前面和空格后面分开(即人名和分数分开)c. 然后遍历每个学生,将人名和分数输出,并求出平均成绩d. 执行完以后要关闭文件。运行结果:试验5.5. 打开第 11 章中讲到的 IOStreamDemo.java 文件,一次读取其中的一行,令每 行形成一个 String 对象。然后利用 接口重新定义 String 对象 间的比较方
40、法:将每个 String 中的小写字母转为大写后再进行比较。使用该比较 法对这些 String 进行排序,按从大到小的顺序存入一个 LinkedList。最后将 LinkedList 中的 String 按存入的相反顺序输出到另一个文件 inverse.txt 中。 import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;class cmp implements Comparator<String> public int compare(String a, Str
41、ing b) String aa=a.toUpperCase(); String bb=b.toUpperCase(); /变成大写字母字符数组 return pareTo(bb); public class stringtest public static void main(String args) BufferedReader br = null;BufferedWriter ww = null;List<String> list = null; try br = new BufferedReader(new FileReader("G:/IOStreamDemo.
42、java");ww = new BufferedWriter(new FileWriter("G:/inverse.txt"); list = new LinkedList<String>();String str =new String120;String aaa=""cmp cmp= new cmp();int i=0;while(stri = br.readLine()!=null) i+=1;for(int j=0;j<i-1;j+)for(int k=0;k<i-1;k+)if(pare(strk,strk+1
43、)<0)aaa=strk;strk=strk+1;strk+1=aaa;for(int j=0;j<i-1;j+) /存入文件list.add(strj);ListIterator it = list.listIterator();while(it.hasNext()it.next();while(it.hasPrevious()ww.write(it.previous().toString(); /输出ww.newLine();ww.flush(); ww.close(); br.close(); catch (FileNotFoundException e) e.printSt
44、ackTrace(); catch (IOException e) e.printStackTrace();设计思路:a. 将文件中的内容读入,然后转化为每行一个字符串,共同组成一个字符串数组b. 将字符串比较大小,比较时将其转化为全部大写,用compareTo进行比较c. 用compareTo的结果将字符串数组进行排序,然后加入到LinkedList中d. 反向输出到文件中去运行结果(部分,详见附件):5.部分结果,详见附件试验6.6、编写能绘制动态正弦波的程序,它绘制的正弦波会不断在窗口中向后滚动, 就像示波器一样。请以线程来控制动画的进行。请提供一个滑块控件,用来控制 动画速度。impo
45、rt java.awt.*;import javax.swing.*;import .*;class Draw extends JPanel implements Runnablestatic final int NumTpoints=200;int Tpoints; /每周期点数int y; /每个点的纵坐标double x; /初始位置Thread thread;double v; /波形速度public void init()/init初始化x = 0;v = 0.05;setBackground(new Color(255,120,120); /线程创建public void start()if(thread=null)thread=new Thread(this); /创建一个新线程thread.sta
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 主题班会教案高一主题班会方案人与环境
- 认识实习报告范文锦集六篇
- 毕业实习报告(集合15篇)
- 在医院的实习报告范文锦集8篇
- 新领域小区配电工程环境保护及文明施工
- 2024至2030年中国割保险带刀片行业投资前景及策略咨询研究报告
- 2024至2030年中国六位半台式万用表行业投资前景及策略咨询研究报告
- 油缸底座课程设计
- 安保述职报告
- 2024年中国风冷热泵式冷水机市场调查研究报告
- 加油站安全检查表分析(SCL)及评价记录
- 丰田车系卡罗拉(双擎)轿车用户使用手册【含书签】
- 幼儿园突发安全事件事故处置措施
- 现代药物制剂与新药研发智慧树知到答案章节测试2023年苏州大学
- 肺结核的学习课件
- 心肺复苏术最新版
- 2023-2024学年贵州省贵阳市小学数学六年级上册期末自测提分卷
- GB/T 9115.2-2000凹凸面对焊钢制管法兰
- 永久避难硐室安装施工组织措施
- 元旦节前安全教育培训-教学课件
- 芯片工艺流程课件1
评论
0/150
提交评论