四、 编程题答案 编程第1题 import java.io.*; public class Point { int x,y;
public Point(int x,int y) { this.x = x; this.y = y; }
public Point getPoint() { Point tempPoint = new Point(x,y); return tempPoint; }
public void setPoint(Point point) { this.x = point.x; this.y = point.y; }
public static void main(String args[]) { Point Point1 = new Point(3,4); System.out.println("Point1:"+"("+Point1.x+","+Point1.y+")");
Point Point2 = Point1.getPoint(); System.out.println("Point2:"+"("+Point2.x+","+Point2.y+")");
Point Point3 = new Point(5,6); Point1.setPoint(Point3); System.out.println("Point1:"+"("+Point1.x+","+Point1.y+")"); }
} 编程第2题 import java.io.*; class FileCopy { public static void main(String[] args) { FileInputStream in; FileOutputStream out;
if (args.length<2) { System.out.println("Usage: java copy srcfile destfile"); System.exit(-1); }
try { in = new FileInputStream(args[0]); out = new FileOutputStream(args[1]); copyFile(in,out);
}
catch (Exception e) { System.out.println(e); }
} private static void copyFile(FileInputStream in, FileOutputStream out) { int length; byte buf[] = new byte[1024]; try{ while ((length=in.read(buf,0,1024))!=-1) { out.write(buf, 0, length); }
}
catch (Exception e) { System.out.println("Error:"+e); System.exit(-1); } }
} 编程第3题 import java.awt.*; import java.awt.event.*; import java.applet.*; import java.util.*; public class TimeViewer extends Applet implements ActionListener, Runnable {
Thread timer; TextField in, out; Button bb; Panel p1, p2, p3; boolean state;
public void init() { in = new TextField(20); out = new TextField(20); bb = new Button("Current Time:"); p1 = new Panel(); p2 = new Panel(); p3 = new Panel();
setLayout(new GridLayout(3, 1)); setSize(200,100);
p1.add(in); p2.add(bb); p3.add(out); add(p1); add(p2); add(p3);
bb.addActionListener(this);
timer = new Thread(this); state = true; timer.start(); }
public void actionPerformed(ActionEvent e) { //out.setText(in.getText()); out.setText(currentTime()); }
public void run() { while(true) { try { timer.sleep(1000); } catch (InterruptedException e) { } in.setText(currentTime());; } }
String currentTime() { Date now = new Date(); String str = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(); return str; } } |