问题 问答题

下面是一个Applet程序,其功能是实现网页上的电子时钟,要求显示的格式为hh:mm:ss如02:04:50。提示:通过获取当前系统时间来实现。请改正程序中的错误(有下划线的语句),使程序能输出正确的结果。 注意:不改动程序的结构,不得增行或删行。 程序运行结果如下:

import java.applet.*; import java.awt.*; import java.util.Date; /* <applet code=”ex9_3.Class”,width;800 height=400> </applet> */ public class ex9_3 extends Applet implements Runnable{ private Thread thTimer:null; private String strTime; private int tHour,tMin,tSec; public void init(){ setFont(new Font("Times New Roman",Font.BOLD,20)); } public void paint(Graphics Graph){ Date dNow = new Date(); tHour = dNow.getHours(); tMin = dNow.getMinutes(); tSec = dNow.getSeconds(); if(tHour<=9)strTime = "0" + tHour + ":" ; elsestrTime = tHour + ":" ; if (tMin<=9)strTime = "0" + strTime + tMin + ":"; elsestrTime = strTime + tMin + ":" ; if(tSec<=9)strTime = "0" + strTime + tSec; elsestrTime = strTime + tSec; Graph.drawString(strTime,80,80); } public void start() { if(thTimer == null) { thTimer = new Thread(); thTimer.start(); } } public void run(){while(thTimer != null){ repaint(); try{ Thread.sleep(1000); } catch (InterruptedException ie){ }} } public void stop () {thTimer = null; } } ex9_3.html <HTML> <HEAD> <TITLE>ex9_3</TITLE> </HEAD> <BODY> <applet code="ex9_3.class"width = 800 height=400> </applet> </BODY> </HTML>

答案

参考答案:

解析:StrTime = strTime + "0" + tMin + ":"strTime = StrTime + "0" + tSecnew Thread(this) 本题主要考查Java多线程与Applet的图形绘制相结合解决实际问题的综合应用。解题关键是熟悉Java多线程的程序设计思想,必须在程序中编写线程类内start(),stop()和run()方法的相关程序,利用线程类的sleep()方法,让每次显示的时间延迟1秒,使电子时钟看起来像是每一秒跳动一次的样子,同时还要熟悉Data类的getHours()等方法获得时间。本题中,包含 2个线程,一个是程序中Runnable得到的线程,另一个是程序本身。第1处和第2处错误相似,一个是在不足10的小时数的前一位补上“0”,如tHour=9,则显示出来的应该是“09”;第三处,用Thread类的构造方法创建新的线程时,需要把this作为参数传递给新的线程,否则程序不会动态执行。

单项选择题 A1型题
填空题