《Java语言程序设计习题答案全集(总--本页仅作为文档封面,使用时请直接删除即可-- --内页可以根据需求调整合适字体及大小--
一)》课后
55页)
( 指出JAVA语言的主要特点和JAVA程序的执行过程。
答:(1)强类型; (2)编译和解释;
(3)自动无用内存回收功能; (4)面向对象; (5)与平台无关; (6)安全性;
(7)分布式计算; (8)多线程;
程序执行过程如图所示:
编写源文件,编译器编译源文件转换成字节码,解释器执行字节码。 说出开发与运行JAVA程序的重要步骤。
答:(1)编写源文件:使用一个文本编译器,如Edit或记事本,不可以使用Word.将编好的源文件保存起来,源文件的扩展名必须是.java;
(2)编译Java源文件:使用Java编译器编译源文件得到字节码文件; (3)运行Java程序:Java程序分为两类——Java应用程序必须通过Java解释器来解释执行其字节码文件;Java小应用程序必须通过支持Java标准的浏览器来解释执行。
如何区分应用程序和小应用程序
答:应用程序在与源文件名字相同的类中,有main()方法,该方法代表应用程序的入口; 小应用程序必须有一个Applet类的子类,该类称作主类,必须用public修饰。
说出JAVA源文件的命名规则。
答:源文件命名规则和类命名规则一样,所有的单词首字母都用大写字母,且必须和源文件的public类同名。
JAVA语言使用什么字符集共有多少个不同的字符
答:Java语言使用Unicode字符集,共有65535个字符。 JAVA语言标识符的命名规则是什么
(1)由字母(包括英文字母、下划线字符、美元字符、文字字符)和数字字符组成
(2)限定标识符的第一个字符不能是数字字符 (3)不能和关键字重名
(4)长度不能超过255个字符
2
JAVA有那些基本数据类型,它们的常量又是如何书写的 数据类型 逻辑类型 整数类型 关键字 字节数 默认值 boolean char byte short int long 常量举例 范围 布尔型 1 false false,true false,true 字符型 字节性 短整型 整型 长整型 单精度浮点 2 1 2 8 8 4 0 0 0 0 0L 0F a,我,ぽ 12,13,45 12,13,45 12,13,45 12L,13L,45L , 0 ~ 65535 -128 ~ 127 -32768 ~ 32767 -2E31 ~ 2E31-1 -2E63 ~ 2E63-1 -10E38 ~ -10E-38 10E-38 ~ 10E38 -10E308 ~ -10E-308 10E-308 ~ 10E308 float 浮点类型 双精度浮double 点 8 0D , 指出下列内容哪些是JAVA语言的整型常量,哪些是浮点数类型常量,哪些两者都不是。
整型常量: 4)0xABCL,8)003,10)077,12)056L
浮点数类型常量:3)-1E-31,5).32E31 13)0.,14).0 两者都不是: 1),2),6),7),9),11)
3
第二章 运算和语句
Java的字符能参加算术运算吗
可以。(1)字符与整型数据运算,结果为整型数据,只能赋给整型变量,如果附给字符型变量会损失精度,需要强制类型装换;
(2)字符与字符运算,结果为字符型数据,可以直接赋给字符型或整型变量。 占字节多的变量能直接赋值给占字节少的变量么 答:不能直接赋值,需要强制类型转换。
试用Java语言表达式描述以下数学计算式或逻辑条件:
3V(43)r1)
解:V = 3)**(r,3); 2)R1(1R11R2) 解:R = / R1+R2);
533)yxx6
解:y = (x,5) + (x,3) + 6;
2FMMR124) 解:F = * M1 * M2 / (R * R); 5)sinx/ax|cosx/2|
解:(x) / a * x + ( (π * x / 2) ); 6)0 < a <10
解:a > 0 && a < 10
7) 条件 x=1 与 y=2 有且只有一个成立.
解:( x == 1 && y != 2) || (x != 1 && y == 2)
设在求以下表达式之前,整型变量a的值是4,试指出在求了以下表达式之后,变量a、b和c的值。
1) 2)
baa;
解:a=5 ; b=16;
caa;;
解:a=5 ; c=10
若一个数恰好等于它的因子之和,则这个数称为“完全数”。编写程序求1000之内的所有完全数。
分析:若一个自然数,它所有的真因子(即除了自身以外的约数)的和恰好等于它本身,这种数叫做完全数。例如6=1+2+3;28=1+2+4+7+14
4
程序运行结果:
/**
* @author 段智敏 */
public class Work2_6 {
public static void main(String[] args) { String resultString = \"1000以内,完全数有:\";
;
/**
* 输入正整数n,输出由n行n列星号字符组成的三角形图案。 * @author 段智敏 */
public class Work2_8 { public static void main(String args[]) { Scanner consoleScanner = new Scanner; \"请输入正整数n:\"); String str = (); int n = -1; try { n = (str); } catch( NumberFormatException e ) { \"输入非法字符,程序结束!!!\"); return; } if (n < 1)
5
}
}
else { }
\"输入的数不是正实数,程序结束!!!\");
for(int i=0;i 量x和y的值分别多少 1)while(x<=y) x*=2; 解:x=160 ;y=110; 2)do{x=y/x; y=y-x;}while(y>=1); 解:x=18; y=0; 求小于999的所有水仙花数。 程序运行结果: 源代码文件: /** * 求小于999的所有水仙花数 * @author 段智敏 */ public class Work2_10 { public static void main(String[] args) { String resultString = new String(\"1000之前的所有水仙花数有: \"); .... /** * 按公式计算:e=1+1/1!+1/2!+1/3!+1/4!+...... 6 * @author 段智敏 */ public class Work2_12 { public static void main(String args[]) { int n = 1000; . 程序运行结果: 源代码文件: /** * 圆周率计算 * @author 段智敏 */ public class Work2_13 { public static void main(String args[]) { int num = 1000000; 类变量 例变量名 对象名.类变量名;类名.类变量名 被实例方法,构造方法访问 被实例方法,类方法,构造方法访问 实例变量、类变量,实例方法、类方法 各个对象之间共享直接分配内存 这段已经分配完的内存 成不分配入口地对象名.实例方员实例方法 共享一个入口地址 址 法名 方7 法 类方法 对象名.类方法直接分配入口共享这个入口地址 名;类名.类方地址 法名 类变量、类方法 子类能继承超类的哪些成员变量和方法 私有(private) 友好(缺省默认) 受保护(protected) 共有(public) 子类在什么情况下能隐藏超类的成员变量和方法 解:子类重载父类的成员变量、方法时候。 在子类中是否允许有一个方法和超类的方法名字相同,而类型不同 解:不允许。方法重写是指:子类中定义一个方法,并且这个方法的名字、返回类型、参数个数、和类型与从父类继承的方法完全相同。 以下程序有什么错误 解:类方法main()调用了类的实例变量,main方法是类方法,不能调用类的实例变量a,导致错误! 声明一个复数类Complex。实现其基本功能。 复数类: /** * 复数类 * @author 段智敏 */ public class Complex { private double 同包继承 不继承 继承 继承 继承 不同包继承(import进来的) 不继承 不继承 继承 继承 real; 8 ength,而确定一个String对 象的长度用对象名.length() 用toUpperCase()和toLowerCase()方法实现大小写转换 答: public class UpperAndLowerTest { public static void main(String args[]) { String s1=(\"ABCdefgHIJkhl123\"),s2,s3; \"未转换时的字符串s1=\"+s1); byte t1[]=(); } { arrayInt[index] = i; index++; } } } /** * 打印数组元素 */ public String printArray() { String result = \"\"; for (int i = 0; i < ; i++) { if (arrayInt[i] != 0) result += arrayInt[i] + \" \"; } return result; } public static void main(String[] args) { Work4_10 w = new Work4_10(100); } 编写实现从两个字符串中找出最长的相同字符列的代码。 程序运行结果: 9 /** * 找出两个字符串中,最长的相同字符列 * @author 段智敏 */ public class Work4_11 { public static void main(String[] args) { String str1 = \"0000abcdef0000\"; String str2 = \"123ab4567cdef789abcdef\"; String str3 = getLongSameString(str1,str2); \"str1 = \" + str1); \"str2 = \" + str2); \"最长的相同字符串为:\" + str3); } public static String getLongSameString(String str1, String str2) { String temp = \"\"; String same = \"\"; String longSame = \"\"; for(int i=0; i<();i++) { for(int j=i+1; j<=();j++) { temp = (i, j); if(temp)>0) { same = temp; if() < ()) { longSame = temp; } } } } return longSame; } } 整理字符串,将字符串的前导空白符和后随空白符删去,并将字符串中非空白字符之间的连接的多个空白符只保留一个,而去掉多余的空白符。 程序运行结果: public class Work4_12 { public static void main(String args[]) { 10 } } String str = \" I Love You \"; str=(); StringTokenizer s=new StringTokenizer(str); String newStr=\"\"; while()){ } \"旧字符串:\"+str); \"处理后新字符串:\"+newStr); newStr=newStr+\" \"+(); 编写用数组实现大整数的类,提供大整数的加、减、乘等运算。 程序运行结果: 大整数类源文件: /** * 大整数类 * @author 段智敏 */ public class MyBigInteger { /** 能存储的最大位数 */ public static final int MAXLENGTH = 100; /** 正负号标识 */ private int signum = 1; /** 实际存储用的数组 */ private int dataArray[]; /** * 将参数的十进制字符串表示形式转换为 BigInteger。 * @param val - 要转换的十进制字符串表示形式。 */ public MyBigInteger(String val) { (val); } 11 /** * 声明一个MAXLENGTH位的,空的大整数类 */ public MyBigInteger() { dataArray = new int[]; } /** * 根据十进制字符串表示形式转换为MyBigInteger的数据 * @param str - 十进制字符串表示形式。 */ public void setData(String str) { dataArray = new int[]; try { int end = 0; signum = 1; if (0) == '-') { signum = -1; end = 1; } int index = 0; for (int i = () - 1; i >= end; i--) { dataArray[index++] = (i))); } } catch( NumberFormatException e ) { (); } } /** * 加法,返回其值为(this + val)的BigInteger。 * @param val- 将添加到此BigInteger中的值。 * @return - this + val */ public MyBigInteger add(MyBigInteger val) { MyBigInteger result = new MyBigInteger(); if > 0 && < 0)ubtract()); } ength() < ().length())ength() == ().length())oString().length(); } /** * 检查进位,做加法时检测 * @param i */ 12 } private void carryBit(int i) { if (i < - 1) [i + 1] += [i] / 10; [i] = [i] % 10; } /** * 检查借位,做减法时检测 */ private void borrowBit(int i) { if (i < - 1) { if [i] < 0) { [i] = [i] + 10; [i + 1]--; } } } 大整数类测试类源文件: import * 大整数测试类 * @author 段智敏 */ public class TestBigInteger { public static void main(String[] args) { String a = \"\"; String b = \"57\"; MyBigInteger m1 = new MyBigInteger(a); MyBigInteger m2 = new MyBigInteger(b); MyBigInteger m3; 13 BigInteger b1 = new BigInteger(a); ; import .*; /** * 创建一个有文本框和三个按钮的程序。当按下某个按钮时,使不同的文字显示在文本框中。 * @author 段智敏 */ public class Work5_7 extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JTextField text; private JButton button1, button2, button3, exit_button; private JPanel panel; public Work5_7() { text = new JTextField(10); button1 = new JButton(\"刘德华\"); button2 = new JButton(\"张学友\"); button3 = new JButton(\"蔡依林\"); exit_button = new JButton(\"退 出\"); (this); (this); (this); (this); panel = new JPanel(); (button1); (button2); (button3); (new FlowLayout()); 14 } (text); (panel); (exit_button); (300, 200); (true); ; } public void actionPerformed(ActionEvent e) { if () == exit_button) { (0); } else { ()); } } public static void main(String args[]) { new Work5_7(); } 编写一个有两个文本框的小应用程序,在第一个文本框输入英语单词,在第二个文本框会自动显示汉语解释;在第一个文本框输入汉语单词,在第二个文本框中显示英语解释。设英语单词表只有少许几个。 程序运行结果: 源文件: import .*; import .*; /** * @author 段智敏 */ public class Work5_8 extends JFrame implements ActionListener ,KeyListener { 15 private static final long serialVersionUID = 1L; private JTextField input_English, input_Chinese; private JLabel label1, label2; private JPanel panel1, panel2; private String[] word_English = { \"moon\", \"star\", \"sun\" };; import .*; import .*; /** * * @author 段智敏 */ public class Work5_9 extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JLabel result_label; private JTextArea input_textArea; private JTextField showResult_textField; private JButton sum_button, average_button, clear_button; private JPanel panelNorth, panelSouth; public Work5_9() { result_label = new JLabel(\"请选择你的操作\"); showResult_textField = new JTextField(12); input_textArea = new JTextArea(); sum_button = new JButton(\"求 和\"); average_button = new JButton(\"平均值\"); clear_button = new JButton(\"清空\"); panelNorth = new JPanel(); panelSouth = new JPanel(); (this); (this); (this); (sum_button); (average_button); (result_label); (showResult_textField); (clear_button); (panelNorth, ; (new JScrollPane(input_textArea), ; (panelSouth, ; 16 (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); (100, 100, 350, 200); (true); (); } public void actionPerformed(ActionEvent e) { if () == clear_button) { (\"\"); (\"\"); (\"请选择你的操作\"); } int number_array[] = getNumber_array(); if () == sum_button) { (\" 输入数的和\"); int sum = 0; for (int i = 0; i < ; i++) sum = sum + number_array[i]; (\"\" + sum); } if () == average_button) { (\"输入数的平均值\"); int sum = 0; for (int i = 0; i < ; i++) sum = sum + number_array[i]; double average = * sum / ; (\"\" + average); } } public int[] getNumber_array() { int numArray[] = null; try { String s = (); String temp = new String(); StringTokenizer t = new StringTokenizer(s, \"'\\n' ,. int n = (); numArray = new int[n]; for (int i = 0; i < n; i++) { temp = (); numArray[i] = (temp); 17 \"); } } } catch( NumberFormatException e ) { (null, \"请确认输入的是数字字符\\n\", \"错误警告\", ; } return numArray; } public static void main(String args[]) { new Work5_9(); } 布局设计 程序运行结果: 源文件: import .*; import .*; /** * @author 段智敏 */ class Work5_10 extends JFrame { private static final long serialVersionUID = 1L; private JPanel panel2, panel3, panel4, panel6; import .*; import * @author 段智敏 */ public class Work6_1 extends JFrame { private static final long serialVersionUID = 1L; ; 18 private MyPanel6_1 panel; import * * @author 段智敏 */ public class Work6_2 extends JFrame { private static final long serialVersionUID = 1L; private MyPanel6_2 panel; public Work6_2() { super(\"第六章,第二题\"); panel = new MyPanel6_2(); (panel); (100, 100, 400, 150); (true); (); (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); } public static void main(String args[]) { new Work6_2(); } } ; 面板类源文件: /** * 需要设计的面板类 */ class MyPanel6_2 extends JPanel implements ItemListener { private static final long serialVersionUID = 1L; private JCheckBox box1, box2, box3, box4; private ButtonGroup group; private JTextField textField; public MyPanel6_2() 19 } { textField = new JTextField(5); group = new ButtonGroup(); box1 = new JCheckBox(\"足球\"); box2 = new JCheckBox(\"排球\"); box3 = new JCheckBox(\"篮球\"); box4 = new JCheckBox(\"台球\"); (this); (this); (this); (this); (box1); (box2); (box3); (box4); (box1); (box2); (box3); (box4); (textField); } public void itemStateChanged(ItemEvent e) { JCheckBox box = (JCheckBox) (); if (box == box1) () + \"\\n\"); else if (box == box2) () + \"\\n\"); else if (box == box3) () + \"\\n\"); else if (box == box4) () + \"\\n\"); } 设计一个面板,该面板中有四个运动项目单选按钮和一个文本框。当某个选择项目被选中时,在文本框中显示该选择项目。 程序运行结果: 源文件: import .*; import .*; 20 import * @author 段智敏 */ public class Work6_3 extends JFrame { private static final long serialVersionUID = 1L; private MyPanel6_3 panel; public Work6_3() { super(\"第六章,第三题\"); panel = new MyPanel6_3(); (panel); (100, 100, 400, 150); (true); (); (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); } public static void main(String args[]) { new Work6_3(); } } 面板类源文件: /** * 需要设计的面板类 */ class MyPanel6_3 extends JPanel implements ItemListener { private static final long serialVersionUID = 1L; private JRadioButton box1, box2, box3, box4; private ButtonGroup group; private JTextField textField; public MyPanel6_3() { textField = new JTextField(5); group = new ButtonGroup(); box1 = new JRadioButton(\"足球\"); box2 = new JRadioButton(\"排球\"); box3 = new JRadioButton(\"篮球\"); box4 = new JRadioButton(\"台球\"); (this); (this); (this); (this); (box1); 21 } (box2); (box3); (box4); (box1); (box2); (box3); (box4); (textField); ; } public void itemStateChanged(ItemEvent e) { JRadioButton box = (JRadioButton) (); if (box == box1) () + \"\\n\"); else if (box == box2) () + \"\\n\"); else if (box == box3) () + \"\\n\"); else if (box == box4) () + \"\\n\"); } 设计一个窗口,取默认布局BorderLayout布局。北面添加一个列表,有4门课程选项。中心添加一个文本区,当选择列表中的某门课程后,文本区显示相应课程的介绍;(JList没有addActionListener方法) 程序运行结果: 源文件: import .*; import .*; /** * @author 段智敏 */ public class Work6_4 extends JFrame { private static final long serialVersionUID = 1L; private JList list; 22 private JTextArea textArea; private String names[] = { \"大学英语\", \"Java语言程序设计\", \"操作系统\", \"数据结构\" }; private String introduce[] = { \"英语为本科一、二年级的最重要的基础课之一,为期一年,教学时间15周,总共14学分。\", \"Java先修课程为程序设计基础、网络基础、数据库基础、操作系统;为期办年。教学时间15周,总共4学分(上机1学分)。\", \"操作系统讲述如何管理计算机系统资源和控制程序执行。为期办年,教学时间15周,总共5学分(上机1学分)。\", \"数据结构是计算机学科的核心课程之一,是一门专业基础课。对于训练学生程序设计能力和编程水平有重要作用。为期办年,教学时间15周,总共5学分(上机学分)\" }; private String times[] = { \"9月1日\", \"9月2日\", \"9月30日\", \"9月12日\" }; public Work6_4() { super(\"第六章,第四题\"); textArea = new JTextArea(5, 10); list = new JList(names); ;; import .*; /** * @author 段智敏 */ public class Work6_5 extends JFrame implements ItemListener { private static final long serialVersionUID = 1L; private String names[] = { \"数学\", \"物理\", \"语文\", \"化学\" }; private JComboBox comboBox; private JTextField textField; public Work6_5() { super(\"第六章,第五题\"); comboBox = new JComboBox(names); (this); textField = new JTextField(10); ; add(comboBox, ; (textField, ; (100, 100, 300, 200); (true); (); (new WindowAdapter() { public void windowClosing(WindowEvent e) { 23 } (0); } }); } public void itemStateChanged(ItemEvent e) { ().toString()); } public static void main(String args[]) { new Work6_5(); } 设计一个JFrame窗口,窗口中心添加一个文本区。另添加4个菜单,每个菜单都有菜单项,每个菜单项都有对应快捷键,选择某个菜单项时,窗口中心的文本区显示相应信息。 程序运行结果: 源文件: import .*; import .*; /** * @author 段智敏 */ public class Work6_6 extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; /** 文本区 */ private JTextArea textArea; /** 菜单条 */ private JMenuBar menubar; /** 菜单:文件、编辑、格式、帮助 */ private JMenu file_menu, edit_menu, format_menu, help_menu, style_menu; /** 添加的文件菜单上的菜单项:新建、打开、保存、另存为、退出 */ private JMenuItem item_newFile, item_openFile, item_saveFile, item_saveAsFile, item_Exit; /** 添加到编辑菜单的菜单项:剪切、复制、粘贴、删除;查找、查找下一个、替换;全选、时间/日期 */ 24 private JMenuItem item_cut, item_copy, item_paste, item_delete, item_find, item_findNext, item_replace, item_selectAll, item_insertNowTime; /** 添加到格式菜单的菜单项:自动换行,换行时候,是否让整个单词在一行,设置字体 */ private JMenuItem item_setLineWrap, item_setWrapStyleWord, item_setFont; /** 帮助菜单项:帮助主题,关于记事本 */ private JMenuItem item_help, item_about; public Work6_6() { super(\"第六章,第六题\"); textArea = new JTextArea(); menubar = new JMenuBar(); (); (menubar); (textArea, ; (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); (100, 100, 500, 400); (true); (); } /** * 初始化菜单项菜单条 并添加快捷键,然后都添加到主菜单条上 */ public void init_menu() { menubar = new JMenuBar(); file_menu = new JMenu(\"文件(F)\"); edit_menu = new JMenu(\"编辑(E)\"); format_menu = new JMenu(\"格式(O)\"); help_menu = new JMenu(\"帮助(H)\"); style_menu = new JMenu(\"风格(G)\"); item_newFile = new JMenuItem(\"新建(N)\"); item_openFile = new JMenuItem(\"打开(O)...\"); item_saveFile = new JMenuItem(\"保存(S)\"); item_saveAsFile = new JMenuItem(\"另存为(A)...\"); item_Exit = new JMenuItem(\"退出(X)\"); item_cut = new JMenuItem(\"剪切(T)\"); item_copy = new JMenuItem(\"复制(C)\"); item_paste = new JMenuItem(\"粘贴(P)\"); item_delete = new JMenuItem(\"删除(L)\"); item_find = new JMenuItem(\"查找(F)\"); item_findNext = new JMenuItem(\"查找下一个(N)\"); item_replace = new JMenuItem(\"替换(R)\"); item_selectAll = new JMenuItem(\"全选(A)\"); item_insertNowTime = new JMenuItem(\"时间/日期(D)\"); 25 item_setLineWrap = new JCheckBoxMenuItem(\"自动换行(W)\", false); item_setWrapStyleWord = new JCheckBoxMenuItem(\"单词为界(S)\", false); item_setFont = new JMenuItem(\"字体(F)...\"); item_help = new JMenuItem(\"帮助主题(H)\"); item_about = new JMenuItem(\"关于记事本(A)\"); import .*; /** * @author 段智敏 */ public class Work6_7 extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; ; private JMenuBar bar;import .*; /** * @author 段智敏 */ public class Work6_8 extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JButton button1, button2; private MyDialog dialog1, dialog2; boolean b1 = false, b2 = false; public Work6_8() { super(\"第六章,第八题\"); button1 = new JButton(\"打开体育之窗\"); button2 = new JButton(\"打开音乐之窗\"); dialog1 = new MyDialog(this, \"体育之窗\", true); ; 26 dialog2 = new MyDialog(this, \"音乐之窗\", true); (this); (this); (new FlowLayout()); (button1); (button2); (true); (150, 150, 200, 200); (); (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); } public void actionPerformed(ActionEvent e) { if () == button1) { if (b1 == false) { (!b1); (\"关闭体育之窗\"); } if (b1 == true) { (!b1); (\"打开体育之窗\"); } b1 = !b1; } else if () == button2) { if (b2 == false) { (!b2); (\"关闭音乐之窗\"); } if (b2 == true) { (!b2); (\"音乐体育之窗\"); } b2 = !b2; } } public static void main(String args[]) { new Work6_8(); 27 } } 对话框类源文件: /** * 窗口 * @author 段智敏 */ class MyDialog extends JDialog { private static final long serialVersionUID = 1L; public MyDialog(JFrame f, String s, boolean mode) { super(f, s, mode); import .*; /** *@author 段智敏 */ public class Work6_9 extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JTextField text1, text2; public Work6_9() { super(\"第六章,第九题\"); text1 = new JTextField(5); text2 = new JTextField(20); (this); (new FlowLayout()); (text1); (text2); (100, 100, 400, 100); (true); (); (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); } public void actionPerformed(ActionEvent e) ; 28 } { int sum = 0; if () == text1) { try { int n = ()); for (int i = 1; i <= n; i++) sum = sum + i; (\"1 ~ \" + n + \"的和为:\" + sum); } catch( NumberFormatException ee ) { (\"输入错误,重新出入\"); (null); } } } public static void main(String args[]) { new Work6_9(); } 编写一个演示鼠标拖动和移动的程序。界面设有一个文本区,当鼠标拖动或移动时,在文本区中输出指明鼠标拖动或鼠标移动,及鼠标位置的字样。 程序运行结果: 源文件: import .*; import .*; /** * @author 段智敏 */ public class Work6_10 extends JFrame implements MouseMotionListener { private static final long serialVersionUID = 1L; private JTextArea text; 29 } public Work6_10() { super(\"第六章,第10题\"); text = new JTextArea(5, 10); (this); (new JLabel(\"鼠标拖动、移动程序\"), ; (text, ; (100, 100, 500, 500); (true); (); (new WindowAdapter() { public void windowClosing (WindowEvent e) { (0); } }); } public void mouseDragged(MouseEvent e) { ; (\"鼠标拖拽:坐标:(\" + () + \ + () + \")\"); } public void mouseMoved(MouseEvent e) { ; (\"鼠标移动:坐标:(\" + () + \ + () + \")\"); } public static void main(String args[]) { new Work6_10(); } 30 第七章 图形、图像和多媒体 编写一个应用程序,绘制一个五角星。 程序运行结果: 源文件: import .*; import .*; /** * 画一个五角星 public class Work7_1 { public static void main(String args[]) { JFrame win = new JFrame(\"第七章,第一题\"); ; (50, 50, 210, 250); (new FiveStarCanvas(100), ; (true); (); } } 画板类源文件: /** * 画板类,在上面画出五角星 * @author 段智敏 */ class FiveStarCanvas extends Canvas { private static final long serialVersionUID = 1L; 31 } /** 五角星外接圆的半径 */ private int radius; /** * 构造方法 * @param r - 初始化外接圆半径 */ public FiveStarCanvas(int r) { = r; } public void paint(Graphics g) { int ax = radius; int ay = 0; int bx = (int) (radius * (1 - ((18 * / 180))); int cx = (int) (radius * (1 + ((18 * / 180))); int dx = (int) (radius * (1 - ((54 * / 180))); int ex = (int) (radius * (1 + ((54 * / 180))); int by = (int) (radius * (1 - ((18 * / 180))); int cy = (int) (radius * (1 - ((18 * / 180))); int dy = (int) (radius * (1 + ((54 * / 180))); int ey = (int) (radius * (1 + ((54 * / 180))); ; (dx, dy, ax, ay); (ax, ay, ex, ey); (ex, ey, bx, by); (bx, by, cx, cy); (cx, cy, dx, dy); ; (0, 0, 2 * radius, 2 * radius); (radius, radius, ax, ay); (radius, radius, bx, by); (radius, radius, cx, cy); (radius, radius, dx, dy); (radius, radius, ex, ey); } 用Graphics2D绘制一条抛物线,设抛物线方程的系数从图形界面输入。 程序运行结果: 32 frame源文件: import .*; import .*; /** * 用Graphics2D画抛物线,抛物线方程的系数从图形界面输入. public class ParabolaFrame extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; 33 private ParabolaCanvas canvas;; import .*; /** * 利用Graphics2D的平移,缩放,旋转功能。绘制一个六角星。 public class Work7_3 extends JFrame { private static final long serialVersionUID = 1L; public Work7_3() { super(\"第七章,第三题\"); (new SixStarCanvas(80), ; (50, 50, 400, 400); (true); (); ; } public static void main(String args[]) { new Work7_3(); } } 画六角形的画板类: /** * 画板类,在上面画出六角星 * 通过先画一个三角形,然后旋转6次,得到六角形 34 class SixStarCanvas extends Canvas { private static final long serialVersionUID = 1L; /** 六角星外接圆的半径 */ private int radius; /** 一个三角形三个顶点的x点坐标集 */ private int xPoints[]; /** 一个三角形三个顶点的y点坐标集 */ private int yPoints[]; /** * 构造方法 * @param r - 初始化外接圆半径 */ public SixStarCanvas(int r) { = r; xPoints = new int[] { r, 2 * r, (int) (3 * r / 2) }; yPoints = new int[] { r, r, (int) (r - (3) * r / 2) }; } public void paint(Graphics g) { Graphics2D g2D = (Graphics2D) g; BasicStroke bs = new BasicStroke(1, , ; (bs); AffineTransform trans = new AffineTransform(); (10, 10);; import .*; /** * 编写画图程序。 * 控制画板的窗口类 * @author 段智敏 */ public class PaintFrame extends JFrame implements ItemListener, ActionListener { private static final long serialVersionUID = 1L; /** 画板 */ private PaintCanvas canvas; /** 画笔端点装饰,无装饰、圆形装饰、方形装饰 */ private JToggleButton cap_butt, cap_round, cap_square; /** 橡皮 */ 35 } private JToggleButton eraser; /** 画笔大小 */ private JComboBox width_box; /** 选择颜色的按钮 */ private JButton selectColor; /** 单选按钮分组 */ private ButtonGroup group; private JPanel panel; private String item[]; private int strokeWidth = 1, strokeCap = 0, strokeJoin = ; public PaintFrame() { super(\"画图小程序\"); canvas = new PaintCanvas(); selectColor = new JButton(\" \"); cap_butt = new JToggleButton(\"标准\"); cap_round = new JToggleButton(\"圆形\"); cap_square = new JToggleButton(\"方形\"); eraser = new JToggleButton(\"橡皮\"); panel = new JPanel(); group = new ButtonGroup(); item = new String[20]; for (int i = 0; i < 20; i++) { item[i] = \"\" + (i + 1); } width_box = new JComboBox(item); (true);oString()); } catch( NumberFormatException e2 ) { strokeWidth = 1; } } (strokeWidth, strokeCap, strokeJoin);oString()); } catch( NumberFormatException e2 ) { strokeWidth = 1; } } (strokeWidth, strokeCap, strokeJoin); } public static void main(String args[]) { new PaintFrame(); } 用来画图的画板类:PaintCanvas import .*; import * 画板类,在上面作图。 36 * @author 段智敏 */ public class PaintCanvas extends Canvas implements MouseMotionListener, MouseListener { 600; private static final long serialVersionUID = 1L; private int x = -1, y = -1; private int w = 800, h = ; import .*; /** * 输入二次曲线的系数以及区间,画出二次曲线 * @author 段智敏 */ public class ConicFrame extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private String helpString = \"三种基本曲线方程:\\n1:椭圆(e<0); 2:双曲线(c<0,e<0); 3:抛物线(a=0或c=0);\"; private BorderLayout borderLayout;写音乐播放器,只能播放 wav,mid格 式的。 程序运行结果: 37 音乐播放器源文件: import .*; import .*; import .*; import .*; import .*; import * 编写音乐播放器,只能播放wav,mid格式的。 * @author 段智敏 */ public class AudioClipFrame extends JFrame implements ItemListener, ActionListener { private static final long serialVersionUID = 1L; /** 组合框,用于存储音频列表 */ private JComboBox comboBox; /** 添加音频时,选择文件的文件对话框 */ private JFileChooser filedialog; /** 按钮:播放、循环、停止、添加、删除 */ private JButton play_button, loop_button, stop_button, open_button, del_button; /** 显示当前播放音频的label */ private JLabel message_label; /** 布局用的panel */ private JPanel list_panel, control_panel; /** 存储添加的音频文件的绝对路径 */ private File fileArray[] = new File[100]; /** 播放用的类 */ private AudioClip clip = null; /** 用来存储当前播放文件的文件名 */ private String fileName; public AudioClipFrame() { super(\"音乐播放器 - 第七章,第六题\"); filedialog = new JFileChooser(\"F:\\\\钢琴曲\\\\midi\"); (new MyFileFilter(\"wav\")); (new MyFileFilter(\"mid\")); list_panel = new JPanel(); control_panel = new JPanel(); comboBox = new JComboBox(); open_button = new JButton(\"添加\"); del_button = new JButton(\"删除\"); play_button = new JButton(\"播放\"); 38 loop_button = new JButton(\"循环\"); stop_button = new JButton(\"停止\"); message_label = new JLabel(\"请添加音频文件\"); ; fileArray[0] = null; (\"\"); (false); (this); (this); (this); (this); (this); (this); (new BorderLayout()); (comboBox, ; (\"音频列表\")); (open_button); (del_button); (play_button); (stop_button); (loop_button); (\"控制按钮\")); (new BorderLayout(20, 10)); (message_label, ; (list_panel, ; (control_panel, ; (300, 200, 450, 190); (true); (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); (); } /** * 设置播放的音频文件 * @param file - 音频文件 */ public void setClipName(File file) { if (file != null) { try { fileName = (); URL url = ().toURL(); clip = (url); } catch( MalformedURLException eee ) 39 } { \"URL错误\"); } } } public void itemStateChanged(ItemEvent e) { if () == comboBox) { int i = ();etName());etName()); } } else if () == del_button) { int index = ();etName()); for (int i = index; i < (); i++) { fileArray[i] = fileArray[i + 1];; if (index > 0 && index < () - 1) { String extension = (index + 1).toLowerCase(); if (postfix)) return true; } return false; } public String getDescription() { if (\"wav\")) return \"Wav 音频文件(*.wav)\"; return \"*.\" + postfix + \"文件\"; } 40 第八章 多线程 建立线程有哪两种方法 答:一是继承Thread类声明Thread子类,用Thread子类创建线程对象。二是在类中实现Runnable接口,在类中提供Runnable接口的run()方法。无论用哪种方法,都需要java基础类库中的Thread类及其方法的支持。程序员能控制的关键性工作有两个方面:一是编写线程的run()方法;二是建立线程实例。 怎样设置线程的优先级 答:setPriority(int p),设定线程的优先级为p(1~10)。线程创建时,子线程继承父线程的优先级。 优先级的数值越大优先级越高(缺省为5)。常用以下3个优先级: (最低) (最高) (标准) 编写程序,一个画圆,一个画椭圆。 程序运行结果: Applet的源文件: import * 用一个红色笔画圆,同时用一个蓝色笔画椭圆 */ public class Work8_3 extends Applet implements Runnable { private static final long serialVersionUID = 1L; /** 两个线程,红笔线程,和蓝笔线程 */ private Thread red_thread, blue_thread; /** 红色画笔、蓝色画笔 */ 41 private Graphics redPen, bluePen; /** 蓝、红笔画时需要旋转角度 */ private int blue_angle = 0, red_angle = 0; /** 红色画的图案的中心坐标 */ private int a_red = 100, b_red = 100; /** 蓝色画的图案的中心坐标 */ private int a_blue = 300, b_blue = 100; /**圆形半径*/ private int radius_red = 80; /**椭圆的两个半径*/ private int radius1_blue = 150, radius2_blue = 100; public void init() { red_thread = new Thread(this); blue_thread = new Thread(this); redPen = getGraphics(); bluePen = getGraphics(); setBackground; setSize(470, 240); } public void start() { (); ; import .*; /** * 线程实现,购票规则,由于我想的算法太过复杂,只写到50元面值的 * @author 段智敏 */ public class BuyTicketFrame extends JFrame implements ActionListener, Runnable { private static final long serialVersionUID = 1L; private Conductor lady; 42 private int array[] = { 10, 10, 5, 20, 50, 5, 5, 5, 5, 5, 5, 10, 20, 10, 5, 10, 20, 5 }; private int number = ; private Thread thread[] = new Thread[number]; static JTextArea text; private JButton begin_button, replay_button; private JPanel panel; public BuyTicketFrame() { super(\"第八章,第六题,线程模拟购票\"); lady = new Conductor(15); text = new JTextArea(); panel = new JPanel(); begin_button = new JButton(\"开始买票\"); replay_button = new JButton(\"重新开始\"); for (int i = 0; i < ; i++) thread[i] = new Thread(this); (this); (this); (new FlowLayout()); (begin_button); (replay_button); (panel, ; (new JScrollPane(text), ; (1000, 700); (true); (); (new WindowAdapter()tart(); if (thread[i].isAlive()) (\" \" + (i + 1) + \"线程开始\\n\"); } ; } catch( IllegalThreadStateException ee ) { (\"error:重复启动线程\" + ()); } sAlive()) break; else n++; } if (n == break; } ;ppend(\"-------------------------------------------------------------------------------\"); \"剩余票数:\" + ticket_amount + \"张:¥:5元:\" + five + \"张;10元:\" + ten + \"张;20元:\" + twenty + \"张;50元:\" + fifty + \"张\\n\"); notifyAll();.生...等...待...☆☆☆☆☆\\n\"); 43 try { wait(); } catch( InterruptedException e ) { } } } if (ticket_amount <= 0) { + \"************售票结束**********\\n\"); return; } else { ticket_amount--; five--; ten++; \"第\" + index + \"个,10元的,找你5元的,给你票\\n\"); } } public void twentyGive(int index).生...等...待...☆☆☆☆☆\\n\"); try { wait(); } catch( InterruptedException e ) { } } } if (ticket_amount <= 0) { + \"************售票结束**********\\n\"); return; } else if (ten >= 1 && five >= 1).生...等...待...☆☆☆☆☆\\n\"); try { wait(); } catch( InterruptedException e ) { } } } 44 ; import .*; /** * 排队买票,主窗口类 * @author 段智敏 * */ public class MainFrame extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; /** 19个顾客的信息,名字,和钱 */ private String name[] = { \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\" }; private int moneies[] = { 10, 10, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5, 5, 5 }; private Customer[] customer; private SalesLady lady; /** 显示信息的文本区,显示售票员信息,和队伍信息 */ private JTextArea text1, text2; /** 开始按钮 */ private JButton start_button; /** 布局用的panel */ private JPanel panel1, panel2; public MainFrame() { super(\"多线程 - 排队 - 买票\"); customer = new Customer[]; lady = new SalesLady; text1 = new JTextArea(); text2 = new JTextArea(); start_button = new JButton(\"开始演示\"); panel1 = new JPanel(); panel2 = new JPanel(); (text1, text2); 45 } (this); (\"信息栏\")); (new GridLayout(1, 2, 10, 10)); (new JScrollPane(text1)); (new JScrollPane(text2)); (start_button); (50, 50, 550, 400); (panel1, ; (panel2, ; (true); (); (new WindowAdapter() { public void windowClosing(WindowEvent e) { (0); } }); } public void actionPerformed(ActionEvent e) { (false); (); for (int i = 0; i < ; i++) { customer[i] = new Customer(name[i], moneies[i], lady);tart(); } } public static void main(String args[]) { new MainFrame(); } 售货员类源文件: import * 售货员类 */ public class SalesLady extends Thread { private int mem, five, ten; n\"; } else if (money == 10) { if (five < 1) { stand_in_a_line(cust); message = (\"售货员:顾客-\" + name + \用10元买物品,没有零钱,请去重新排队,\" + name + \"很无奈的去排队了\\n\"); } else { 46 mem--; five--; ten++; amount--; message = \"售货员:顾客-\" + name + \",成功购买1个纪念品,你给我10块,我找你5块!\\n\"; } } return message; } public void setJTextArea(JTextArea text1, JTextArea text2) { = text1; = text2; } } 顾客类源文件: /** * 顾客类 */ public class Customer extends Thread { private String name; private int money; private SalesLady lady; public Customer(String name, int money, SalesLady lady) { super(name); = name; = money; = lady; } /** * 得到顾客排队序号 * @return - 序号 */ public String getCustomerName() { return ; } /** * 得到顾客付的钱数 * @return - 钱 */ public int getMoney() { return ; } 47 } public String toString() { return ; } public void run() { try { (this); (10); } catch( InterruptedException e ) { } } 链队列类源文件: /** * 队列的链式存储 * @author 段智敏 */ public class LinkQueue { /** 队列头 */ private Node front; /** 队列尾 */ private Node rear; public LinkQueue() { Node p = new Node(); front = p; rear = p; } /** * 入队列操作 * @param obj - 要入队的数据 */ public void enQueue(Object obj) { Node p = new Node(obj);etData(); } } /** * 得到队头的引用 * @return 返回队头元素的引用 * @throws Exception */ public Node getHeadNode() throws Exception { 48 } if (isEmptyQueue()) throw new Exception(\"error:队列为空,不能操作!\"); else { return front; } } /** * 打印出队列的所有元素 */ public String printQueue() { String result = \"\"; Node p = (); while (p != null) { result += ().toString() + \" \"); p = (); } return result; } 链式存储结点类源文件: package ; /** * 链式存储时候,用的结点类 */ public class Node { /** 此结点的后继结点的引用 */ private Node next; /** 此结点的数据 */ private Object data; /** * 无参数构造方法,后继引用和数据都为null */ public Node() { = null; = null; } /** * 直接设置此结点数据的构造方法 * @param obj - 该结点的数据 */ public Node(Object obj) { = null; = obj; 49 } /** * 同时设置该结点的后继结点,和数据 * @param obj - 该结点的数据 * @param next - 该结点的后继结点的引用 */ public Node(Object obj, Node next) { = next; = obj; } /** * 设置后继结点的引用 * @param n - 该结点的后继结点 */ public void setNext(Node n) { = n; } /** * 得到其后继结点的引用 * @return 返回结点引用 */ public Node getNext() { return next; } /** * 设置其数据 * @param obj - 数据 */ public void setData(Object obj){ = obj; } /** * 得到数据,object类型 * @return 返回数据 */ public Object getData() { return ; } /** * 得到此数据的字符串形式 */ public String toString() { 50 } } return (); 51 第九章 输入和输出流 一个文本,一个按钮。在文本区中输入数据,点击按钮,将文本内容输出到文件。文件通过文件保存对话框制定。 程序运行结果: 保存文件的源文件: import .*; import .*; import .*; /** * 一个文本,一个按钮。 * 在文本区中输入数据,点击按钮,将文本内容输出到文件。 public class SaveFile extends JFrame implements ActionListener { private static final long serialVersionUID = 1L;ength()); (); } catch( Exception e ) { (\"写文件发生错误\"); } } public static void main(String[] args) { new SaveFile(); } } 52 在一个文件中,每行存的是整数,各行整数个数不等,要求读这个文件,然后计算每行整数的和,并存到另一个文件中。 程序运行结果: 计算文件中的整数和源文件: import .*; import .*; import .*; import .*; /** * 在一个文件中,每行存的是整数,各行整数个数不等, * 要求读如这个文件,然后计算每行整数的和,并存到另一个文件中。 public class FileIntegerSum extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JButton buttonSave, buttonCount, buttonOpen;.\"); buttonCount = new JButton(\"计算结果\"); label = new JLabel(\" \"); panel = new JPanel(); textArea = new JTextArea(); filedialog = new JFileChooser(); (new MyFileFilter(\"txt\")); (this); (this); (this);ength())); (); (); } catch( FileNotFoundException e2 ) { (\"文件没有找到\\n\"); } catch( IOException e3 ) { } } /** * 计算指定文件上,每行整数之和,并显示在文本区上 53 * @param file - 指定的文件 */ public void countResult(File file) { try { FileReader file_reader = new FileReader(file); BufferedReader in = new BufferedReader(file_reader); String temp = new String(); while ((temp = ()) != null) { int number = 0; StringTokenizer token = new StringTokenizer(temp, \" ,.\"); while ()) { number += ()); } (temp + \"---------相加结果是:\" + number + '\\n'); } (); } catch( Exception e2 ) { (\"error\" + e2 + '\\n'); } } public static void main(String args[]) { new FileIntegerSum(); } } 在一个文本区中输入数据,把输入的数据分析成各个单词,然后排序显示到第二个文本区中,并通过文件保存对话框保存到文件中。 程序运行结果: 源文件: import .*; 54 import .*; import .*; import .*; /** * 在一个文本区中输入数据,把输入的数据分析成各个单词, * 然后排序显示到第二个文本区中,并通过文件保存对话框保存到文件中. public class SortString extends JFrame implements CaretListener, ActionListener { private static final long serialVersionUID = 1L; private JTextArea input_text;.\"); panel1 = new JPanel(); panel2 = new JPanel(); label = new JLabel(\" \"); (true); (false); (this); (this); (this); (clear_button); (save_button); (new JScrollPane(input_text)); (new JScrollPane(showResult_text2)); (panel1, ; (panel2, ; (label, ; (20, 20, 700, 400); (); (true); ; } public void caretUpdate(CaretEvent e) { String string = (); StringTokenizer fenxi = new StringTokenizer(string, \" ();:.,.,'\\n''\'\"); int n = (); String arrayStr[] = new String[n]; for (int i = 0; i < n; i++) { String temp = (); arrayStr[i] = temp; } (arrayStr);ength())); (); (); } catch( FileNotFoundException e2 ) { (\"文件没有找到\"); } 55 } catch( IOException e3 ) { (); } } public static void main(String args[]) { new SortString(); } 在一个文本区中输入数据,将文本区中的数据存入文件中,在又用户指定的序号,程序从文件中读取对应序号数据,输出到文本框中。 程序运行结果: 源文件: import .*; import .*; /** * 在一个文本区中输入数据,将文本区中的数据存入文件中 * 在又用户指定的序号,程序从文件中读取对应序号数据,输出到文本框中。 public class Work9_5 extends JFrame implements ActionListener, ItemListener { private static final long serialVersionUID = 1L; private JButton buttonSave;ength())); (); (); readFile(file); } catch( FileNotFoundException e ) { (\"文件没有找到\"); } catch( IOException e ) 56 } { (); } } /** * 按行读取文件,并保存, * @param file - 指定的文件 */ public void readFile(File file) { try { FileReader file_reader = new FileReader(file); BufferedReader in = new BufferedReader(file_reader); String ss = new String(); int i = 0; while ((ss = ()) != null) { (\"第\" + (i + 1) + \"行\"); stringArray[i] = ss; i++; } (stringArray[0]); (); } catch( FileNotFoundException e ) { (\"文件没有找到\"); } catch( IOException e ) { (); } } public static void main(String args[]) { new Work9_5(); } 一个文本区,一个按钮,点击按钮选择文件,然后又把文件中的内容输入到文本区中。 程序运行结果: 57 打开文件原文件: import .*; import .*; /** * 一个文本区,一个按钮,点击按钮选择文件,然后又把文件中的内容输入到文本区中。 public class OpenAndShowFile extends JFrame implements ActionListener { private static final long serialVersionUID = 1L;; if (index > 0 && index < () - 1) { String extension = (index + 1).toLowerCase(); if (postfix)) return true; } return false; } /**显示在文件类型上的文字*/ public String getDescription() { return \"*.\" + postfix + \"文件\"; } } 58 第十章 网络与数据库编程基础 程序中,用何种对象存储IP地址和域名 答:用InetAddress类的对象 用代码示意程序获取域名和IP地址的方法。 答: Import .*; Class Example10_1{ Public static void main(String args[]){ Try{ TYPE_SCROLL_SENSITIVE,游标可上下移动,当数据库变化时,当前结果集同步改变。 int 型参数concurrency决定数据库是否与可滚动集同步更新 ,不能用结果集更新数据库中的表。 ,能用结果集更新数据库中的表。 说出实现数据库查询的方法。 答:利用 Connection对象的createStatement方法建立Statement对象,利用Statement对象的executeQuery()方法执行SQL查询语句进行查询,返回结果集,再利用getXXXX()的方法从结果集中读取数据。 59 因篇幅问题不能全部显示,请点此查看更多更全内容
* @author 段智敏 */
* @author 段智敏 */
* @author 段智敏 */
* @author 段智敏 */
* 文件通过文件保存对话框制定。
* @author 段智敏 */
* @author 段智敏 * */
* @author 段智敏 */
* @author 段智敏 */
* @author 段智敏 */