下面是一个Applet程序,其功能是接收用户输入的两个整数,比较它们的大小,并在用户按下“比较大小”按钮后,将Applet中显示的“请先输入两个待比较的整数”,改为“两个整数中最大值是:x”,x是两个数中的最大值。请改正程序中的错误(有下划线的语句),使程序能输出正确的结果。 注意:不改动程序的结构,不得增行或删行。 import java. applet. *; import java. awt. * import java. awt. event. *; /* <applet code= LookForMax width= 800 height= 400> </applet> */ public class LookForMax extends Applet implements ActionListener{ Label result; TextField in1,in2 Button btn; int a=0,b=0,max=0; public void init() { result=new Label( "请先输入两个待比较的整数"); in1 = new TextField(5); in2 = new TextField (5) btn = new Button("比较大小"); add(in1); add(in2) add(btn) add(result) btn. addActionListener(super) } public void actionPerformed(ActionEvent e){ a=Integer. parseInt(in1); b=Integer. parselnt(in2); if (a>b)max=a; elsemax=b; result . setText("两个数中最大值是: "+max); } } LookFormax. html; <html> <head> <title>A Simple Program</title> </head> <body> <applet code="LookForMax, class" width 800 height=400> </applet></body></html>
参考答案:
解析:thisin1.getText()in2.getText() 本题主要考查Java Applet程序的编写、java.awt包的基本组件的使用及super和this关键字的使用。Applet(小程序)是一种很重要的 Java程序,是工作在Internet的浏览器上或借助 JDK中的appletviewer来工作的Java程序。编写Applet小程序必须要用到java.applet包中的 Applet类。java.applet.Applet是java.awt.Panel的子类。在本题中,public class LookForMax extends Applet implements ActionListener语句的功能是声明一个继承Applet类且实现ActionListener接口的类LookForMax来实现程序功能,btn.addActionListener(this);语句的功能是为按钮btn对象注册一个事件监听器this(this是指当前LookForMax的对象),a=Integer.parseInt (in 1.getText());和b=Integer.parseInt(in 2.getText());语句的功能是把从文本框in1和 in2获得的字符型数据转换成基本整型数据,并把这两个值分别赋给变量a和b。