BITJava实验2.docx_第1页
BITJava实验2.docx_第2页
BITJava实验2.docx_第3页
BITJava实验2.docx_第4页
BITJava实验2.docx_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

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

文档简介

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: instead 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 dont need to worry about dealing with invalid parameter values. 2) Show the additional code you would add to the above methods to throw an exception if n is less than zero (you dont 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 doesnt need to 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 specifying 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 implemented 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 calculate() pisum=0.0; /初始化void caln(int n) pisum=0.0;for(double i=0;i=n);System.out.println(PiSum=+pisum); static void test1(int a) throws myexception if(a0) throw new myexception(a); /若a=0) System.out.println(Using Iteration:); example.caln(n); System.out.println(Using Recursion:); System.out.println(PiSum=+example.digui(n); catch(myexception e) System.out.println(Caught +e.getmyexception(); System.out.println(); System.out.println(in put a precision value); str=buf.readLine(); precision=Double.parseDouble(str); example.calprecision(precision); 设计思路:a. 精度算法按照题目要求写,当1/(2*n+1) 小于精度的时候即可停止。b. 自定义exception,规定当输入的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, 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 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 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) Square 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 length 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 java.lang.Math.PI c) Write 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) 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) System.out.println(Coordinate before move:+(+x+,+y+); x+=a; y+=b; System.out.println(Coordinate after move:+(+x+,+y+); public void print() System.out.println(Coordinate:(+x+,+y+); class Square extends shapeint lenth;protected Square(int a,int c,int d)super(c,d);lenth=a;void area() int s; s=lenth*lenth; System.out.println(Area of Square:+s); void circumference() int l; l=4*lenth; System.out.println(Circumference of Square:+l); public void print() super.print(); System.out.println(Lenth of sides:+lenth); area(); circumference(); class Circle extends shapeint r,x,y;protected Circle(int n,int c,int d)super(c,d);r=n;void area()double s; s=(java.lang.Math.PI)*r*r; System.out.println(Area of Circle:+s); void circumference()double l; l=2*java.lang.Math.PI*r; System.out.println(Circumference of Circle:+l); public void print() super.print(); System.out.println(Nradius:+r); area(); circumference(); public class test public 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;i2;i+)System.out.println(Square +i+:); example1i.print(); System.out.println(); for(int j=0;j2;j+)System.out.println(Circle +j+:); example2j.print(); System.out.println();设计思路:a. 建立抽象类Shape的子类Square和Circle, Shap(int a, int b)构造方法为初始化坐标(a,b),子类Square/Circle(inta,intb,intc)则为(边长/半径,横坐标,纵坐标)。b. 在Shape中声明抽象方法area()和circumference(),在每个子类中重写,分别重写对应的计算方法。c. 每个类以及方法均按照题目要求权限设置,并注意在子类中也要是同样的设置。运行结果:实验2试验3.3编写程序,从命令行参数读取一个字符串,然后 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; System.out.println(Please Input a String); count=System.in.read(buffer); count-=2; for(int i=0;icount;i+) if(bufferi!=buffercount-i-1) flag=true; if(count-ibestk) break; k=1; for(int j=i+1;jbufferj-1) k+=1; else break; if(kbestk) bestk=k; System.arraycopy(buffer,i,buf,0,bestk); if(flag) System.out.println(This String is Not a Palindrome); else System.out.println(This String is a Palindrome); System.out.println(The Longest Ascending Subsequence is:); for(int h=0;hbestk;h+) System.out.print(char)bufh); 设计思路:a. 输入流将字符串分成字符数组记录下来。b. 将字符串数组头尾进行比较,若头尾对称相等,则为回文,反之则不是。c. 循环比较,记录当前最长的递增子序列,直到将字符串数组遍历以后,方可得出最长子序列。运行结果:3.1 是回文输入3.2 不是回文输入试验4.4. You are asked to write a student marks 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 , one student per line. For example: Smith 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 new 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 standard 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 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 StudentRecord 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 java.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) System.err.println(File not found.);public Vector readFile() String line = new String();/ create a buffered reader so we can read in a lineBufferedReader inFile = new BufferedReader(fs);Vector stu = new Vector();try while (line = inFile.readLine() != null) int posi = line.indexOf(t);/找到空格前边是名字后边是分数String name = line.substring(0, posi - 1);int score = Integer.parseInt(line.substring(posi + 1);stu.add(new StudentRecord(name,score);/变成StudentRecord然后加入到stu中 catch (IOException e) System.err.println(IO exception);/ close the filetry inFile.close(); catch (IOException e) System.err.println(IO exception);return stu;Marksmain:import java.util.Iterator;import java.util.Vector;import java.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 fileName = 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 = (StudentRecord) marks.elementAt(i);System.out.println(entry.getName() + t + entry.getMark();/输出流中的学生信息averageSum += entry.getMark();System.out.println(Average + averageSum / marks.size();/输出平均成绩/ print out each students mark on a separate line in the/ format: Student Name mark/ at the end print 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 对象。然后利用 java.util.Comparator 接口重新定义 String 对象 间的比较方法:将每个 String 中的小写字母转为大写后再进行比较。使用该比较 法对这些 String 进行排序,按从大到小的顺序存入一个 LinkedList。最后将 LinkedList 中的 String 按存入的相反顺序输出到另一个文件 inverse.txt 中。 import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.LinkedList;import java.util.List;import java.util.ListIterator;import java.io.BufferedWriter;import java.io.FileWriter;import java.util.Comparator;import java.lang.Math;class cmp implements Comparator public int compare(String a, String 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 list = null; try br = new BufferedReader(new FileReader(G:/IOStreamDemo.java);ww = new BufferedWriter(new FileWriter(G:/inverse.txt); list = new LinkedList();String str =new String120;String aaa=;cmp cmp= new cmp();int i=0;while(stri = br.readLine()!=null) i+=1;for(int j=0;ji-1;j+)for(int k=0;ki-1;k+)if(pare(strk,strk+1)0)aaa=strk;strk=strk+1;strk+1=aaa;for(int j=0;ji-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.printStackTrace(); catch (IOException e) e.printStackTrace();设计思路:a. 将文件中的内容读入,然后转化为每行一个字符串,共同组成一个字符串数组b. 将字符串比较大小,比较时将其转化为全部大写,用compareTo进行比较c. 用compareTo的结果将字符串数组进行排序,然后加入到LinkedList中d. 反向输出到文件中去运行结果(部分,详见附件):5.部分结果,详见附件试验6.6、编写能绘制动态正弦波的程序,它绘制的正弦波会不断在窗口中向后滚动, 就像示波器一样。请以线程来控制动画的进行。请提供一个滑块控件,用来控制 动画速度。import java.awt.*;import javax.swing.*;import javax.swing.event.*;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.start(); /运行该线程 /正弦波运动public void run()while(Thr

温馨提示

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

评论

0/150

提交评论