题共 5 小题,每空 2 分,共 20 分) 27.方法 boolean isPrime(int n)的功能是判断正整数 n(n>1)是否为质数。 static boolean isPrime(int n) { int i; if(n==2)return true; if(n%2==0)return false; for(i=3;i*i<=n;i+=2) if(__n%i=0_______) break; if(___i*i>n______) return true; return false; }
28.某小应用程序窗口中有一个文本框,一个 8 行 10 列的文本区以及一个按钮,点击这个按钮时,在文本框中输入的内容会追加到文本区中。 import java.applet.*; import javax.swing.*; import java,awt.event.*; public class TextAPP extends Applet implements ActionListener { JTextField input; JTextArea display; JButton append; public void init() { input = new JTextField(10); display = new JTextArea(8,10) ; append = new JButton("追加"); add(input); add(display); add(append); input.requestFocus(); display.setLineWrap(true); append.addActionListener(this); } public void actionPerformed(ActionEvent e),{ display. append (input.getText() +" "); } } 29.某小应用程序有一个由 3 个单选按钮组成的颜色选择组, 当选中某种颜色时, 窗口的背景颜色将作相应的变化。 这里给出的是窗口子类 My Window 的定义的框架以及其构造函数的定义。 class MyWindow extends JFrame implements ItemListener { … MyWindow(String s) { super(s); Container con = this.getContentPane(); con.setLayout(new GridLayout(3,2)); this.setLocation(100, 100); this.setSize(400, 400); panel 1 = new Panel l (); label l = new JLabel("改变前景颜色",JLabel.CENTER); con.add(label 1 ); con. Add(panell) ; panel 1 .box 1 .addltemListener(this); panel 1 .box 2.addItemListener(this); panel 1 .box 3.addItemListener(this); this. setVisible (true); this.pack(); } … } 30.某小应用
程序的界面有两个按钮,点击“画圆”按钮,程序在窗口画一个圆,点击“画矩形”按钮,程序在窗
口画一个矩形。 import java.applet.*; import java.awt.*; import java.awt.event.*;import javax.swing.*; public class Class l extends Applet implements ActionListener { boolean c = false; int r = 50,a = 50, b = 50; JButton bl, b2; public void init(){ setSize(200, 200); setBackground(Color.blue); b1 = new JButton("画 圆"); b2 = new JButton("画矩形"); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); setVisible(true); } public void paint (Graphics g){ g.clearRect(70, 100, 130, 200); g.setColor(Color. red); if(c) g.drawRoundRect(70, 100, r, r, r, r); else g.drawRect(70, 100, a, b); } public void update(Graphics g){ paint(g); } public void actionPerformed(ActionEvent e){ if(e.getSource()==b1) { c = true; } else if(e.getSource()==b2){ c = false; } repaint() ; } }
31.某按钮的监视器方法 actionPerformed()实现将文本区中的内容写入到文本文件 myText.txt 中。 public void actionPerformed(ActionEvent e) { try { int n = txtFld.getText().length(); byte buffer[]=new byte[n]; buffer=txtFid.getText().getBytes(); FileOutputStream wf=new ("myText.txt"); wf. write(buffer, 0,n); FileOutputStream Wf,close() ; }catch (IOException ioe){ txtFld.setText(ioe.toString()); } } } 五、程序分析题(本大题共 5 小题,每小题 4 分,共 20 分) 32.阅读下列程序,请写出该程序的输出结果。答:obj1.m=10 public class A { int m = 5; static int n = 3; public static void main(String[] args) { A obj 1 = new A(); A obj2 = new A(); objl.m *= 2; objl.n *= 4; obj2.m += 1; obj2.n += 6; System.out.println("obj 1.m='' + obj 1.m); System.out.println("obj 1.n=" + obj 1.n); System.ou