Object eventSource = e.getSource(); if(eventSource == menuItem[0]) //新建动作 { textArea.setText(""); } else if(eventSource == menuItem[1])//打开动作 { openFileDialog.setVisible(true); fileName = openFileDialog.getDirectory()+openFileDialog.getFile(); if(fileName != null) { openFile(fileName); } } else if(eventSource ==menuItem[2])//保存动作 { saveFileDialog.setVisible(true); fileName = saveFileDialog.getDirectory()+saveFileDialog.getFile(); if(fileName !=null) { writeFile(fileName); } } else if(eventSource==menuItem[14])//退出动作 { System.exit(0); } else if(eventSource == menuItem[4]||eventSource == menuItem1[5]) //全选动作 { textArea.selectAll(); } else if(eventSource == menuItem[5]||eventSource == menuItem1[2]) //复制动作 { String text = textArea.getSelectedText(); StringSelection selection= new StringSelection(text); clipboard.setContents(selection,null); } else if(eventSource == menuItem[6]||eventSource == menuItem1[1])//剪切动作 { String text = textArea.getSelectedText(); StringSelection selection = new StringSelection(text); clipboard.setContents(selection,null); textArea.replaceRange("", textArea.getSelectionStart(), textArea.getSelectionEnd()); }

else if(eventSource == menuItem[7]||eventSource == menuItem1[3])//粘贴动作 { Transferable contents = clipboard.getContents(this); if(contents==null) return; String text; text=""; try { text = (String)contents.getTransferData(DataFlavor.stringFlavor); } catch(Exception ex) {

} textArea.replaceRange(text, textArea.getSelectionStart(),textArea.getSelectionEnd()); } else if(eventSource == menuItem[8]) //自动换行 { if (textArea.getLineWrap()) textArea.setLineWrap(false); else textArea.setLineWrap(true);

} else if(eventSource == menuItem[9]) //字体 {//实例化字体类

FontDialog fontdialog = new FontDialog(new JFrame(),"字体",true); textArea.setFont(fontdialog.showFontDialog()); //设置字体 }

else if(eventSource == menuItem[11]) //帮助 { try { String filePath = "C:/WINDOWS/Help/notepad.hlp"; Runtime.getRuntime().exec("cmd.exe /c "+filePath); } catch(Exception ee) { JOptionPane.showMessageDialog(this,"打开系统的记事本帮助文件出错!","错误信息",JOptionPane.INFORMATION_MESSAGE); } } else if(eventSource == menuItem[12]) //关于记事本 { String help = "记事本 版本1.0\n操作系统:WIN 8 \n编译器:eclipse\n版权" + "所有: ESTON YANG \n最终解释权归本人所有" + "" + "\nBuild By 冯洋" + "\n课程设计:JAVA"; JOptionPane.showConfirmDialog(null, help, "关于记事本", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);

} else if(eventSource == menuItem[15]||eventSource == menuItem[16]) //查找下一个 { search();

} else if(eventSource == menuItem[17]) //替换 { substitude(); } else if(eventSource == menuItem[3]) //打印 { try { textArea.print(); } catch (PrinterException e1) { e1.printStackTrace(); }

} } /** * openFile方法 * * 从TXT读进数据到记事本 * **/ public void openFile(String fileName){

try {

File file = new File(fileName); FileReader readIn = new FileReader(file); int size = (int)file.length(); int charsRead = 0; char[] content = new char[size]; while(readIn.ready()) { charsRead += readIn.read(content,charsRead,size-charsRead); } readIn.close(); textArea.setText(new String(content,0,charsRead)); } catch(Exception e) { System.out.println("Error opening file!"); } } /** * saveFile方法 * * 从记事本写进数据到TXT * **/ public void writeFile(String fileName){ try { File file = new File(fileName); FileWriter write = new FileWriter(file); write.write(textArea.getText()); write.close(); } catch(Exception e) { System.out.println("Error closing file!"); } } /** * substitude方法 * * 实现替换功能 * */ public void substitude() {

final JDialog findDialog = new JDialog(this, "查找与替换", true); Container con = findDialog.getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel searchContentLabel = new JLabel("查找内容(N) :"); JLabel replaceContentLabel = new JLabel("替换为(P) :"); final JTextField findText = new JTextField(30); final JTextField replaceText = new JTextField(30); final JCheckBox matchcase = new JCheckBox("区分大小写(C)"); ButtonGroup bGroup = new ButtonGroup(); final JRadioButton up = new JRadioButton("向上(U)"); final JRadioButton down = new JRadioButton("向下(D)"); down.setSelected(true); //默认向下搜索

bGroup.add(up); bGroup.add(down);

JButton searchNext = new JButton("查找下一个(F)"); JButton replace = new JButton("替换(R)"); final JButton replaceAll = new JButton("全部替换(A)");

//"替换"按钮的事件处理

replace.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (replaceText.getText().length() == 0 && textArea.getSelectedText() != null)

textArea.replaceSelection(""); if (replaceText.getText().length() > 0 && textArea.getSelectedText() != null)

textArea.replaceSelection(replaceText.getText()); } });

//"替换全部"按钮的事件处理

replaceAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textArea.setCaretPosition(0); //将光标放到编辑区开头 int a = 0, b = 0, replaceCount = 0; if (findText.getText().length() == 0) { JOptionPane.showMessageDialog(findDialog, "请填写查找内容!", "提示",JOptionPane.WARNING_MESSAGE); findText.requestFocus(true); return; } while (a > -1) { int FindStartPos = textArea.getCaretPosition();//获取光标位置

String str1, str2, str3, str4, strA, strB; str1 = textArea.getText(); str2 = str1.toLowerCase(); str3 = findText.getText(); str4 = str3.toLowerCase(); if (matchcase.isSelected()) //大小写区分 { strA = str1; strB = str3; } else { strA = str2; strB = str4; }

if (up.isSelected()) //向上搜索

{ if (textArea.getSelectedText() == null) { a = strA.lastIndexOf(strB, FindStartPos1); } } else //向下搜索

{ if (textArea.getSelectedText() == null) { a = strA.indexOf(strB, FindStartPos);

} else { a = strA.indexOf(strB, FindStartPos- findText.getText().length() + 1); } }

if (a > -1) { if (up.isSelected()) {

textArea.setCaretPosition(a); b = findText.getText().length(); textArea.select(a, a + b); } else if (down.isSelected()) {

textArea.setCaretPosition(a); b = findText.getText().length(); textArea.select(a, a + b); } } else { if (replaceCount == 0) { JOptionPane.showMessageDialog(findDialog,"找不到您查找的内容!", "记事本",JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(findDialog, "成功替换"+ replaceCount + "个匹配内容!", "替换成功",JOptionPane.INFORMATION_MESSAGE); } } if (replaceText.getText().length() == 0&& textArea.getSelectedText() != null) //用空字符代替选定内容

{

textArea.replaceSelection(""); replaceCount++; } if (replaceText.getText().length() > 0&& textArea.getSelectedText() != null) //用指定字符代替选定内容 {

textArea.replaceSelection(replaceText.getText()); replaceCount++; } }//end while } });

//"查找下一个"按钮事件处理

searchNext.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { int a = 0, b = 0; int FindStartPos = textArea.getCaretPosition(); String str1, str2, str3, str4, strA, strB; str1 = textArea.getText(); str2 = str1.toLowerCase(); str3 = findText.getText(); str4 = str3.toLowerCase();

//"区分大小写"的CheckBox被选中

if (matchcase.isSelected()) //区分大小写

{ strA = str1; strB = str3; } else //不区分大小写 { strA = str2; strB = str4; } if (up.isSelected()) //向上搜索

{ if (textArea.getSelectedText() == null) {

a = strA.lastIndexOf(strB, FindStartPosfindText.getText().length()findText.getText().length() + 1); } } if (a > -1) { if (up.isSelected()) {

textArea.setCaretPosition(a); b = findText.getText().length(); textArea.select(a, a + b); } else if (down.isSelected()) {

textArea.setCaretPosition(a); b = findText.getText().length(); textArea.select(a, a + b); } } else { JOptionPane.showMessageDialog(null, "找不到您查找的内容!", "记事本", JOptionPane.INFORMATION_MESSAGE); } } });

//"取消"按钮及事件处理

JButton cancel = new JButton("取消"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { findDialog.dispose(); } }); //创建"查找与替换"对话框的界面

JPanel bottomPanel = new JPanel(); JPanel centerPanel = new JPanel(); JPanel topPanel = new JPanel(); JPanel direction = new JPanel();

direction.setBorder(BorderFactory.createTitledBorder("方向")); direction.add(up); direction.add(down);

JPanel replacePanel = new JPanel(); replacePanel.setLayout(new GridLayout(1, 2)); replacePanel.add(searchNext); replacePanel.add(replace); replacePanel.add(replaceAll); replacePanel.add(cancel);

topPanel.add(searchContentLabel); topPanel.add(findText);

centerPanel.add(replaceContentLabel); centerPanel.add(replaceText); centerPanel.add(replacePanel);

bottomPanel.add(matchcase); bottomPanel.add(direction);

con.add(replacePanel); con.add(topPanel); con.add(centerPanel); con.add(bottomPanel);

//设置"查找与替换"对话框的大小、可更改大小(否)、位置和可见性

findDialog.setSize(550, 240); findDialog.setResizable(true); findDialog.setLocation(230, 280); findDialog.setVisible(true); }//方法mySearch()结束 /** * search方法 * * 实现查找功能 * */ public void search() {

final JDialog findDialog = new JDialog(this, "查找下一个", true); Container con = findDialog.getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel searchContentLabel = new JLabel(" 查找内容(N) :");

final JTextField findText = new JTextField(17); final JCheckBox matchcase = new JCheckBox("区分大小写(C)"); ButtonGroup bGroup = new ButtonGroup(); final JRadioButton up = new JRadioButton("向上(U)"); final JRadioButton down = new JRadioButton("向下(D)"); down.setSelected(true); //默认向下搜索

bGroup.add(up); bGroup.add(down);

JButton searchNext = new JButton("查找下一个(F)");

//"查找下一个"按钮事件处理

searchNext.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { int a = 0, b = 0; int FindStartPos = textArea.getCaretPosition(); String str1, str2, str3, str4, strA, strB; str1 = textArea.getText(); str2 = str1.toLowerCase(); str3 = findText.getText(); str4 = str3.toLowerCase();

//"区分大小写"的CheckBox被选中

if (matchcase.isSelected()) //不区分大小写

{ strA = str1; strB = str3; } else //区分大小写 { strA = str2; strB = str4; } if (up.isSelected()) //向上搜索

{ if (textArea.getSelectedText() == null) {

a = strA.lastIndexOf(strB, FindStartPosfindText.getText().length()findText.getText().length() + 1); } } if (a > -1) { if (up.isSelected()) {

textArea.setCaretPosition(a); b = findText.getText().length(); textArea.select(a, a + b); } else if (down.isSelected()) {

textArea.setCaretPosition(a); b = findText.getText().length(); textArea.select(a, a + b); } } else { JOptionPane.showMessageDialog(null, "找不到您查找的内容!", "记事本", JOptionPane.INFORMATION_MESSAGE); } } });

//"取消"按钮及事件处理

JButton cancel = new JButton(" 取消 "); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { findDialog.dispose(); } }); //创建"替换"对话框的界面

JPanel bottomPanel = new JPanel(); JPanel centerPanel = new JPanel(); JPanel topPanel = new JPanel(); JPanel direction = new JPanel(); direction.setBorder(BorderFactory.createTitledBorder("方向")); direction.add(up); direction.add(down); topPanel.add(searchContentLabel); topPanel.add(findText); topPanel.add(searchNext); bottomPanel.add(matchcase); bottomPanel.add(direction); bottomPanel.add(cancel); con.add(topPanel); con.add(centerPanel); con.add(bottomPanel); //设置"替换"对话框的大小、可更改大小(否)、位置和可见性

findDialog.setSize(425, 200); findDialog.setResizable(true); findDialog.setLocation(230, 280); findDialog.setVisible(true); }

/** * 主函数 * * * **/ public static void main(String[] args) {

MiniNote note = new MiniNote(); note.setVisible(true); }

} //字体类

import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.border.*; import java.util.*; public class FontDialog {

private Dialog fontdialog; private JButton okButton, cancelButton; private int width = 480; private int height = 250; private String name = "Serif"; private int type = 0; private int size = 12; private Font customFont = new Font("宋体", Font.ITALIC, 12); private boolean okpressed = false; private boolean cancelpressed = false; private JLabel lbl1 = new JLabel("字体:"); private JLabel lbl2 = new JLabel("字形:"); private JLabel lbl3 = new JLabel("大小:"); private JTextArea area; String[] zx = { "常规", "加粗", "斜体", "基线" }; String[] dx = {"8" , "9" , "10", "12", "14", "15", "16", "18",

"20", "21", "22", "24", "26", "28", "30", "36",

"48", "54","72" , "89"}; JLabel lbl = new JLabel("字体样式Style"); private JComboBox cb1, cb3 = new JComboBox(dx), cb2 = new JComboBox(zx); private String[] zt;

public FontDialog(Frame owner, String title, boolean modal) {

init(); fontdialog = new Dialog(owner, title, modal); fontdialog.setLocation(owner.getLocation()); fontdialog.setLayout(new FlowLayout()); fontdialog.setSize(getWidth(), getHeight()); fontdialog.add(lbl1); fontdialog.add(cb1); fontdialog.add(lbl2); fontdialog.add(cb2); fontdialog.add(lbl3); fontdialog.add(cb3); fontdialog.add(okButton); fontdialog.add(cancelButton); fontdialog.add(area); fontdialog.setResizable(false); fontdialog.setAlwaysOnTop(true); cancelButton.addActionListener(new fontListener()); okButton.addActionListener(new fontListener()); fontdialog.addWindowListener(new fontListener());

cb1.addItemListener(new ItemListener() { // public void itemStateChanged(ItemEvent event) { //获取选择用户的字体类型

name = (String) event.getItem(); setCustomFont(new Font(name, type, size)); } });

cb2.addItemListener(new ItemListener() { // public void itemStateChanged(ItemEvent event) { //获取选择用户的字形

String s = (String) event.getItem(); if (s.equals("常规")) { type = Font.PLAIN; setCustomFont(new Font(name, type, size)); } else if (s.equals("加粗")) { type = Font.BOLD;

字体动作 添加监听器字形动作 添加监听器 setCustomFont(new Font(name, type, size)); } else if (s.equals("斜体")) { type = Font.ITALIC; setCustomFont(new Font(name, type, size)); } else { type = Font.CENTER_BASELINE; setCustomFont(new Font(name, type, size)); } } });

cb3.addItemListener(new ItemListener() { //大小动作 public void itemStateChanged(ItemEvent event) { //添加监听器获取选择用户的字号大小

size = (new Integer((String) event.getItem()).intValue()); setCustomFont(new Font(name, type, size)); } });

}

public Font showFontDialog() { fontdialog.setVisible(true); if (okpressed) { return getCustomFont(); } else { return customFont; } }

private void init() { //初始化 okButton = new JButton("确定"); cancelButton = new JButton("取消"); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); zt = ge.getAvailableFontFamilyNames(); cb1 = new JComboBox(zt); cb1.setMaximumRowCount(6); area = new JTextArea(6, 30); cb3 = new JComboBox(dx); cb3.setMaximumRowCount(6); okButton.setFocusable(true); area.setEditable(false); area.setText(new Date().toString()); area.setBorder(new TitledBorder("字体样式")); }

public void setWidth(int width) { this.width = width; }

public void setHeight(int height) { this.height = height; }

private int getWidth() { return (this.width); }

private int getHeight() { return (this.height); }

private void setCustomFont(Font customFont) //{ this.customFont = customFont; area.setFont(customFont); area.revalidate(); }

public String toString() { return FontDialog.class.toString(); }

设置字体 public Font getCustomFont() //获取字体 { return (this.customFont); }

private class fontListener extends WindowAdapter implements ActionListener //监听事件类 { public void windowClosing(WindowEvent e) { fontdialog.dispose(); }

public void actionPerformed(ActionEvent e) { if (e.getSource() == cancelButton) { fontdialog.dispose(); cancelpressed = true; } else if (e.getSource() == okButton) { okpressed = true; setCustomFont(new Font(name, type, size)); fontdialog.dispose(); } } } }

学 生 实 验 报 告 册

(理工类)

课程名称:面向对象程序设计 专业班级:16计算机科学与技术(专转本)

学生学号: 1613203022 学生姓名: 张义丹

所属院部: 计算机工程 指导教师: 刘 晶

20 16 ——20 17 学年 第 2 学期

金陵科技学院教务处制 实验报告书写要求

实验报告上交电子稿,标题采用四号黑体,正文采用小四号宋体,单倍行距。

实验报告书写说明

实验报告中实验目的和要求、实验仪器和设备、实验内容与过程、实验结果与分析这四项内容为必需项。教师可根据学科特点和实验具体要求增加项目。

填写注意事项

(1)细致观察,及时、准确、如实记录。 (2)准确说明,层次清晰。

(3)尽量采用专用术语来说明事物。

(4)外文、符号、公式要准确,应使用统一规定的名词和符号。 (5)应独立完成实验报告的书写,严禁抄袭、复印,一经发现,以零分论处。

实验报告批改说明

实验报告的批改要及时、认真、仔细,一律用红色笔批改。实验报告的批改成绩采用五级记分制或百分制,按《金陵科技学院课堂教学实施细则》中作业批阅成绩评定要求执行。

实验项目名称:Java编程基础 实验学时: 6 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.3.21~17.4.4 实验成绩: 批改教师: 刘晶 批改时间:

1

实验1 Java编程基础

一、实验目的和要求

(1) 熟练掌握JDK1.6及Eclipse4.2编写调试Java应用程序及Java小程序的方法; (2) 熟练掌握Java应用程序的结构;

(3) 了解Java语言的特点,基本语句、运算符及表达式的使用方法; (4) 熟练掌握常见数据类型的使用;

(5) 熟练掌握if-else、switch、while、do-while、for、continue、break、return语句的使用方法;

(6) 熟练掌握数组和字符串的使用;

(7) 调试程序要记录调试过程中出现的问题及解决办法;

(8) 编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;

(9) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。

三、实验过程

(1)分别使用JDK命令行和Eclipse编译运行Java应用程序;适当添加注释信息,通过javadoc生成注释文档;为主方法传递参数“Hello world”字符串,并输出,记录操作过程。

public class Hello { public static void main(String args[]) { System.out.println("Hello!"); } } (2)分别使用JDK命令行和Eclipse编译Java Applet,并建立HTML文档运行该Applet。压缩生成".jar"文件。记录操作过程。 import java.awt.*; import java.applet.Applet; public class HelloApplet extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.drawString("Hello!",20,20); }

2

} (3) 根据变量score中存放的考试分数,输出对应的等级。要求从键盘输入学生成绩, 60分以下为D等;60~69为C等;70~89为B等;90~100为A等。 (4) 编写一个Java Application程序,输出区间[200,300]上的所有素数,将其用数组prime[]保存,并以每10个一行的形式显示运行结果。 (5)输出下列数字形式,要求用二维数组完成。 ①n=4 0 0 0 0 0 1 1 1 0 1 2 2 0 1 2 3 ② n=4 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 (6) 求二维数组的鞍点,即该位置上的元素在该行上最大,在列上最小。也可能无鞍点。 (7) 分析下列程序的输出结果,掌握equals()方法和“= =”的区别。 class StringTest2{ public static void main(String args[]) {

String s1 = "This is the second string.";

String s2 = "This is the second string.";

String s3 = new String("This is the second string.");

String s4 = new String(s1);

String s5 = s1;

boolean result121 = s1.equals(s2);

boolean result122 = s1 == s2;

boolean result131 = s1.equals(s3);

boolean result132 = s1 == s3;

boolean result141 = s1.equals(s4);

boolean result142 = s1 == s4;

boolean result151 = s1.equals(s5);

boolean result152 = s1 == s5;

System.out.println("s1 equals s2= " +result121);

System.out.println("s1 == s2= " +result122);

System.out.println("s1 equals s3= " +result131);

System.out.println("s1 == s3= " +result132);

System.out.println("s1 equals s4= " +result141);

3

System.out.println("s1 == s4= " +result142);

System.out.println("s1 equals s5= " +result151);

System.out.println("s1 == s5= " +result152); } } (8) 判断回文字符串

回文是一种“从前向后读”和“从后向前读”都相同的字符串。如“rotor”是一个回文字符串。

程序中使用了两种算法来判断回文字符串:

算法一:分别从前向后和从后向前依次获得原串str的一个字符ch

1、ch2,比较ch1和ch2,如果不相等,则str肯定不是回文串,yes=false,立即退出循环:否则继续比较,直到字符全部比较完,yes的值仍为true,才能肯定str是回文串。

算法二:将原串str反转成temp串,再比较两串,如果相等则是回文字符串。 (9) 使用String类的compareTo(String s)方法,对以下字符串从小到大排序:“melon”, “apple”, “pear”, “banana”,显示输出排序结果。

要求:

(1) 编译调试程序之前应配置好环境变量;

(2) 要分别掌握用JDK命令行和Eclipse集成开发环境调试Java程序; (3) 注意Java两大类程序:应用程序和小程序的区别。

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。)

(1)主方法传递参数“Hello world”字符串,并输出

public class Hello { public Hello(){

System.out.println("HelloWorld!"); } public static void main(String args[]){

new Hello(); } } (2)Eclipse编译Java Applet import java.awt.*; import java.applet.Applet; public class HelloApplet extends Applet { int height,width; public void init(){

this.height=100;

this.width=300; }

4

public void paint(Graphics g){

g.setColor(Color.red);

g.drawString("Hello!", 20, 20); } } (3)

package b; import java.util.Scanner; public class Test { public static void main(String args[]){

int score;

//char grade;

System.out.println("请输入分数按回车");

Scanner reader=new Scanner(System.in);

score=reader.nextInt();

if(score>=90&&score<=100){

System.out.println("A");

}

else if(score>=70&&score<=89){

System.out.println("B");

}

else if(score>=60&&score<=69){

System.out.println("C");

}

else if(score<60){

System.out.println("D");

}

else{

System.out.println("数据错误");

} } } (4)

public class Lim { public static void main(String[] args) {

int[] prime = calculation(20, 200, 300);

for (int i = 0; i < prime.length; i++) {

if (prime[i] != 0) {

if (i % 10 == 0 && i != 0)

System.out.println();

System.out.print(prime[i] + " ");// 打印数据

}

}

5

} public static int[] calculation(int length, int start, int end) {

int j;

int step = 0;

int[] prime = new int[length];

for (int i = start; i <= end; i++)

{

j = 2;

while (i % j != 0) {

j++;

}

if (j == i)

{

prime[step] = i;

step++;

}

}

return prime;

} } (5) ① public class shuzu { public static void main(String args[]){

int i,j;

int arr[][]=new int[4][];

for(i=0;iarr[i]=new int[arr.length]; for(i=0;i<4;i++)

for(j=3;j>=i;j--){

arr[i][j]=i;

} for(j=0;j<4;j++){

for(i=3;i>=j;i--){

arr[i][j]=j;

} }

for(i=0;i<=3;i++){

for(j=0;j<=3;j++){

System.out.print(arr[i][j]);

System.out.print(" ");

}

System.out.println();

6

}

} } ②public class Shuzu { public static void main(String args[]){ int num[][]=new int[4][]; for(int i=0;inum[i]=new int[2*i+1];

for(int m=0;mSystem.out.print(" ");

}

int k=i+1;

for(int j=0;jif(j<=i)

num[i][j]=j+1;

else{

k--;

num[i][j]=k;

}

System.out.print(num[i][j]+" ");

}

System.out.println(); } } } (6) public class test { public static void main(String[] args) {

// TODO Auto-generated method stub

int[][] mat = {{11,12,13},{4,5,6},{7,8,9}};

for (int i=0;i{

for(int j=0;jSystem.out.print(mat[i][j]+" ");

System.out.println();

}

boolean find = false; //找到鞍点标记

int row=0; //第1行下标

int max=0; //记录当前行最大值的列下标

while (!find && row{

max=0; //初始设每行第1列值最大

for (int j=1;j7

if (mat[row][j]>mat[row][max]) //mat[row][max]为该行最大值

max = j;

boolean yes = true; //再判断mat[row][max]是否在列上最小

int j=0;

while (yes && j{

if(mat[j][max]yes=false;

j++;

}

if (yes)

find = true;

else

row++;

}

if (find)

System.out.println("The dort: "+mat[row][max]);

else

System.out.println("The dort: null"); } } (8) import java.util.Scanner; public class HuiWenTest { public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("请输入一个字符串"); @SuppressWarnings("resource")

Scanner input = new Scanner(System.in); String str = input.next(); StringBuilder sb=new StringBuilder(str); sb.reverse();//将Sr倒置的方法 String newStr=new String(sb); if(str.equals(newStr)){ System.out.println(str+"是回文字符串"); }else{ System.out.println(str+"不是回文字符串"); } } } (9) import java.util.*; public class SortString { public static void main(String[] args) {

// TODO Auto-generated method stub

String [ ] a={"melon","apple","pear","banana"};

8

String [ ] b=Arrays.copyOf(a,a.length); System.out.println("使用用户编写的SortString类,按字典序排列数组a:"); SortString.sort(a); System.out.println("排序结果是:"); for(String s:a) { System.out.print(" "+s); } System.out.println(""); System.out.println("使用类库中的Arrays类,按字典序排列数组b:"); Arrays.sort(b); System.out.println("排序结果是:"); for(String s:b) { System.out.print(" "+s); } }

四、实验结果与分析(程序运行结果及其分析)

(1)

9

(2)

10

(3)

(4)

(5)

(6)

(7)

11

(8)

(9)

五、实验体会(遇到问题及解决办法,编程后的心得体会)

在这次实验中,我知道了eclipse和jdk运行程序的区别,jdk比较麻烦一些,需要配置变量。在实验中,配置jdk的环境变量要注意它的path和 classpath,如果classpath本身就有,可以在后面加分号,这样不影响其它的classpath的使用。学会了如何生成注释文档,主函数传递参数的方法,还有压缩文件,实验中还对数组的创建和使用进行了练习,还有一些类的应用。

12

实验项目名称: 面向对象编程 实验学时: 8 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.4.11~17.5.2 实验成绩: 批改教师: 刘晶 批改时间:

13

实验2 面向对象编程

一、实验目的和要求

(1)熟练掌握Java语言类定义的基本语法; (2)熟练掌握类成员的访问控制,对象建立的方法; (3)熟练掌握类构造方法、成员方法的定义和重载; (4)熟练掌握类继承、多态和抽象性; (5)熟练掌握接口的定义和实现方法; (6)掌握基本的异常处理方法;

(7)调试程序要记录调试过程中出现的问题及解决办法;

(8)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;

(9) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。

三、实验过程

(1)定义一个Man类,保存在Man.java文件中,类中包含说话方法如下: public class Man

{

public void say()

{

System.out.println(“我是中国人!”);

}

} 为此类打包为cn.edu.jit.chinese;再在Man.java文件所在路径下,创建一个China.java文件,其中定义China类如下: public class China

{

public static void main(String[] args)

{

Man lihua = new Man();

lihua.say();

}

}

在China类中引用Man类,输出显示“我是中国人!”。试着去掉Man类的public修饰,看看会发生什么情况?

(2)设计复数类,成员变量包括实部和虚部,成员方法包括实现复数加法、减法、字符串描述、比较是否相等等操作。

14

(3)包的建立与使用:设计计算器类Calculator,计算加、减、乘、除和立方体体积,并且打包为mypackage。观察源文件目录下是否生成了mypackage文件夹,在该文件夹中是否有Calculate.class文件。编辑PackageDemo.java,保存在Calculator.java同一目录下,引用计算器类的各方法显示计算结果。

(4)试编码实现简单的银行业务:处理简单帐户存取款、查询。编写银行帐户类BankAccount,包含数据成员:余额(balance)、利率(interest);操作方法:查询余额、存款、取款、查询利率、设置利率。再编写主类UseAccount,包含main()方法,创建BankAccount类的对象,并完成相应操作。

(5)假定根据学生的3门学位课程的分数决定其是否可以拿到学位,对于本科生,如果3门课程的平均分数超过60分即表示通过,而对于研究生,则需要平均超过80分才能够通过。根据上述要求,请完成以下Java类的设计: 1)设计一个基类Student描述学生的共同特征。

2)设计一个描述本科生的类Undergraduate,该类继承并扩展Student类。 3)设计一个描述研究生的类Graduate,该类继承并扩展Student类。

4)设计一个测试类StudentDemo,分别创建本科生和研究生这两个类的对象,并输出相关信息。

(6)设计三角形类,继承图形抽象类,计算三角形面积和周长。

(7)试编码实现多态在工资系统中的应用:给出一个根据雇员类型利用abstract方法和多态性完成工资单计算的程序。Employee是抽象类,Employee的子类有Boss(每星期发给他固定工资,而不计工作时间)、CommissionWorker(除基本工资外还根据销售额发放浮动工资)、PieceWorker(按其生产的产品数发放工资)、HourlyWorker(根据工作时间长短发放工资)。该例的Employee的每个子类都声明为final,因为不需要再继承它们生成子类。在主测试类Test中测试各类雇员工资计算结果。

提示:对所有雇员类型都使用earnings()方法,但每个人挣的工资按他所属的雇员类计算,所有雇员类都是从超类Employee派生出的。在超类中声明earnings()为抽象方法,并且对于每个子类都提供恰当的earnings()的实现方法。为了计算雇员的工资,程序仅仅使用雇员对象的一个超类引用并调用earnings()方法。在一个实际的工资系统中,各种Employee对象的引用可以通过一个Employee引用数组来实现。程序依次使用数组的每个元素(Employee引用)调用每个对象的earnings()方法。 Employee类定义如下: abstract class Employee { private String firstName; private String lastName; public Employee(String first,String last) {

15

firstName=first; lastName=last; } public String getEmployeeName() { return firstName; } public String getLastName() { return lastName; } public String toString() { return firstName+lastName; } public abstract String earnings(); } (8)设计圆柱体类和圆椎体类,继承圆类Circle并实现体积接口Volume,计算表面积和体积。

(9)定义一个接口CanFly,描述会飞的方法public void fly();分别定义飞机类和鸟类,实现CanFly接口。定义一个测试类,测试飞机和鸟。测试类中定义一个makeFly(CanFly obj)方法,让会飞的事物飞起来(即调用相应类的fly()方法)。然后在main方法中创建飞机对象和鸟对象,并在main方法中调用makeFly(CanFly obj)方法,让飞机和鸟起飞。

(10)异常的捕获:计算两数相除并输出结果。使用三个catch子句,分别捕捉输入输出异常、除数为0的异常和参数输入有误异常。 import java.io.*; class Ex1 { public static void main(String args[ ]) { try{ BufferedReader strin=new BufferedReader( new InputStreamReader(System.in));//建立输入流缓冲区 System.out.print("请输入除数:"); String cl=strin.readLine();//键盘输入 int a=Integer .parseInt(cl); System .out .print("请输入被除数:"); cl=strin .readLine(); int b=Integer .parseInt(cl); int c=b/a; System .out .println("商为:"+c); } //捕获与I/O有关的异常(空白处补全捕获语句)

16

//捕获数值转化时的异常,如不能将字符转化成数值

//捕获除数为0的异常

} } 编译并运行,当产生输入输出异常时显示异常信息;当输入除数为0时,出现算术异常,提示除数为0,并要求重新输入;当输入的不是整数时,如将30输成了3o,出现数值格式异常,提示输入整数。

(11)编写程序包含自定义异常MyException,当100被13和4除时抛出该异常,其余除数显示商值。

要求:

(1) 注意选用适当的类成员修饰符(private、protected、public等),比较它们的使用情况;

(2) 养成良好的编程习惯,严格按照命名规则为包、类及类成员命名,将每个程序打包,包的命名方式如two.num1表示实验二的第一题;

(3) 学会使用Eclipse的各种调试方法;

(4) 学会查阅Java API文档,如查找异常类的使用方法。

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。) (1) package cn.edu.jit.chinese;// 为Man类打包为cn.edu.jit.chinese public class Man { public void say() {

System.out.println("我是中国人!"); } } package cn.edu.jit.chinese;

import cn.edu.jit.chinese.*; //导入包

public class China { public static void main(String[] args) {

Man lihua = new Man();//主方法先创建类然后调用类

lihua.say(); } } (2)public class Complex { private double real,image; //定义私有的real,image public Complex(double real,double image)

17

{this.real=real; //赋值

this.image=image;} public Complex(double real) {this(real,0);} public Complex() {this(0,0);} public Complex(Complex c) {this(c.real,c.image);} public double getReal() {return real;} public void setReal(double real) {

this.real = real;} public double getImage() {

return image;} public void setImage(double image) {

this.image = image;} public Complex add(Complex c1,Complex c2)//写方法

{Complex C=new Complex(c1.real+c2.real,c1.image+c2.image); return C;} public Complex add(Complex c1) {Complex C=new Complex(this.real+c1.real,this.image+c1.image); return C; } public Complex jian(Complex c1,Complex c2) {Complex C=new Complex(c1.real-c2.real,c1.image-c2.image); return C; } public Complex jian(Complex c1) {Complex C=new Complex(this.real-c1.real,this.image-c1.image); return C; } public boolean bijiao(Complex c1,Complex c2) {return (c1.real==c2.real&&c1.image==c2.image); } public boolean bijiao(Complex c1) {return (c1.real==this.real&&c1.image==this.image); } public String toString() {return this.real+"+"+this.image+"i";} } public class ComplexText { public static void main(String[] args) {

Complex c1=new Complex(2,5); //创建类,调用类里面的方法

18

Complex c2=new Complex(5,2);

Complex c3=new Complex();

System.out.println(c3.add(c1,c2));

System.out.println(c3.jian(c1,c2));

System.out.println(c3.bijiao(c1,c2));} } (3)public class Calculate { double i,j, t; public Calculate(int i,int j) {this.i=i; this.j=j;} public Calculate(int i,int j,int t) {this.i=i; this.j=j;this.t=t;} public double add() {return i+j;} public double jian() {return i-j;} public double cheng() {return i*j;} public double chu() {return i/j;} public double tiji() {return i*i*i+j*j*j+t*t*t;} } public class PackageDemo {//测试

public static void main(String[] args) {

Calculate c1=new Calculate(8,4);

Calculate c2=new Calculate(8,4,2);

System.out.println("相加="+c1.add());

System.out.println("相减="+c1.jian());

System.out.println("相乘="+c1.cheng());

System.out.println("相除 ="+c1.chu());

System.out.println("立方体体积="+c2.tiji());} } (4)public class BankAccount { double balance,interest,cunkuan; public BankAccount(double cunkuan,double balance)//写方法

{this.balance=balance;

this.cunkuan=cunkuan;} public void set(double cunkuan)

19

{if(cunkuan<10000) interest=0.1;

else if(cunkuan<50000) interest=0.25;

else if(cunkuan<100000) interest=0.035;

else interest=0.5; } public double get()

{ return interest;} public void chaxun(double balance,double cunkuan)

{System.out.println("存款为:"+cunkuan);

System.out.println("余额为:"+balance);} public void qu(double qukuan)

{System.out.println("取款为:"+qukuan); System.out.println("得到的利润率:"+(this.cunkuan-qukuan)*this.interest);} } public class UseAccount {//测试

public static void main(String[] args) {

BankAccount c1=new BankAccount(40000,40000);

c1.chaxun(40000,20000);

c1.set(20000);

System.out.println("利率为"+c1.get());

c1.qu(10000);} } (5)public class Student { String name; int age; float average,chainese; float math,Enghish; public Student(String name,int age) {this.name=name;this.age=age; System.out.println(name+":"+age+"岁"+" ");} public void set(float chinese,float math,float Enghish) {average= (chinese+math+Enghish)/3;} public float get() {return average;} }

class Undergraduate extends Student// Student继承Undergraduate {public Undergraduate(String name,int age){ super(name,age); }

20

public void hege(float average){

this.average=average;

if(average>=60) System.out.println("本科生成绩合格"); else System.out.println("本科生成绩不合格");}}

class Graduate extends Student// Student继承Graduate {public Graduate(String name,int age){ super(name,age);//调用

} public void hege(float average){ this.average=average; if(average>=80) System.out.println("研究生生成绩合格"); else System.out.println("研究生成绩不合格");} } public class StudentDemo {//测试

public static void main(String[] args) {

Undergraduate c1=new Undergraduate("小明 ",22);

System.out.println("本科生三门成绩分别为:"+"59,"+"85,"+"90");

c1.set(65,75,60);

System.out.println("本科生平均分="+c1.get());

c1.hege(c1.get());

System.out.println();

Graduate c2=new Graduate("小红 ",18);

System.out.println("研究生生三门成绩分别为"+"90,"+"84,"+"88");

c2.set(80,86,79);

System.out.println("研究生生平均分="+c2.get());

c2.hege(c2.get()); } (6) public abstract class ClosedFigure {//定义抽象类

String shape; public ClosedFigure(String newShape) {this.shape=newShape;} public abstract double perimeter();//定义抽象类,里面不能写方法

public abstract double area(); } public class Triangle extends ClosedFigure {// ClosedFigure继承Triangle double a,b,c; public Triangle(String newShape,double a,double b,double c) {super("newShape"); this.a=a; this.b=b;

21

this.c=c;} public double perimeter() {return a+b+c;} public double area() {double s; s=(a+b+c)/2; return Math.sqrt(s*(s-a)*(s-b)*(s-c));} public String toString() {return ("三角形三边长:"+a+" "+b+" "+c+" "+"周长:"+perimeter()+"面积:"+area());} public class Test { public static void main(String[] args) {

Triangle c1=new Triangle("三角形",3,4,5);

c1.perimeter();

c1.area();

System.out.println(c1.toString());} } } (7)public abstract class Employee { private String firstName; private String lastName; public Employee(String first,String last)

{firstName=first;

lastName=last; } public String getEmployeeName()

{return firstName;} public String getLastName()

{ return lastName;} public String toString()

{return firstName+lastName;} public abstract String earnings(); } public final class Boss extends Employee{ double salary; public Boss(String first, String last, double salary) { super(first, last);

this.salary = salary;} public String earnings() {return (salary+"");} } public final class CommissionWorker extends Employee { double salary;

22

double sale; double price; public CommissionWorker(String first, String last, double salary, double sale,double price) {

super(first, last);

this.salary = salary;

this.sale = sale;

this.price = price; } public String earnings() {return (salary+sale*price+"");} } public final class PieceWorker extends Employee{

double number;

double price;

public PieceWorker(String first, String last, double number,double price) {

super(first, last);

this.number = number;

this.price=price;

}

public String earnings()

{return (number*price+"");}

} public final class HourlyWorker extends Employee {double time; double money; public HourlyWorker(String first, String last, double time, double money) { super(first, last); this.time = time; this.money = money; } public String earnings() { return (time*money+"");} } public class Test { public static void main(String[] args) {

Employee c1=new Boss("张","三",10000);

System.out.println("张三月工资:"+c1.earnings());

Employee c2=new CommissionWorker("李","四",4000,1500,2);

System.out.println("李四月工资:"+c2.earnings());

23

Employee c3=new PieceWorker("王","五",1000,3);

System.out.println("王五月工资:"+c3.earnings());

Employee c4=new HourlyWorker("刘","三",600,30);

System.out.println("刘三月工资:"+c4.earnings()); } } (8)public class Circle { String shape; double r; double height; double pi; public Circle(String shape,double r,double height,double pi) {this.shape=shape; this.height=height; this.r=r; this.pi=pi;} } public interface Volume { public abstract double area(); public abstract double NewVolume(); } public class Yuanzhu extends Circle implements Volume { public Yuanzhu(String shape, double r, double height, double pi) { super(shape, r, height, pi); } public double area() { return pi*r*r;} public double NewVolume() {return area()*height;} } public class Yuanzhui extends Yuanzhu implements Volume { public Yuanzhui(String shape, double r, double height, double pi) {

super(shape, r, height, pi);

// TODO Auto-generated constructor stub } double s; public double area() {s=Math.sqrt(height*height+r*r); return pi*r*s+pi*r*r;} public double NewVolum() {return 1.0/3*pi*r*pi*r*height;} } public class Test { public static void main(String[] args) {

Yuanzhu c1=new Yuanzhu("圆柱",4,6,3.14);

24

Yuanzhui c2=new Yuanzhui("圆锥",2,3,3.14);

System.out.println("圆柱表面积:"+c1.area());

System.out.println("圆柱体积:"+c1.NewVolume());

System.out.println("圆锥表面积:"+c2.area());

System.out.println("圆锥体积:"+c2.NewVolume());} } (9) public interface CanFly {//定义接口CanFly public void fly(); } public class Plane implements CanFly{//使用接口 @Override public void fly() {

// TODO Auto-generated method stub

System.out.println("飞机借助螺旋桨飞上天空"); } } public class Bird implements CanFly{ @Override public void fly() {

// TODO Auto-generated method stub

System.out.println("小鸟 借助翅膀飞上天空"); } } public class Test { static void makeFly(CanFly obj){

obj.fly(); } public static void main(String[] args) {

// TODO Auto-generated method stub

CanFly p =new Plane();

makeFly(p);

CanFly b =new Bird();

makeFly(b); } } (10) import java.io.*; public class Ex1 { public static void main(String args[ ]) { try{ BufferedReader strin=new BufferedReader( new InputStreamReader(System.in));//建立输入流缓冲区

System.out.print("请输入除数:"); String cl=strin.readLine();//键盘输入

25

int a=Integer .parseInt(cl); System .out .print("请输入被除数:"); cl=strin .readLine(); int b=Integer .parseInt(cl); int c=b/a; System .out .println("商为:"+c); } //捕获与I/O有关的异常(空白处补全捕获语句)

catch(IOException e) {System.out.println("输入输出异常");} //捕获数值转化时的异常,如不能将字符转化成数值

catch(NumberFormatException e) {System.out.println("数值格式异常,重新输入");

} //捕获除数为0的异常

catch(ArithmeticException e) {System.out.println( "除数为0,重新输入");} } } (11)(1)MyException类: package exp2_11; public class MyException extends Exception{ MyException (String msg){

super(msg); } } (2)Div主类: package exp2_11; import java.io.*; public class Div { public static void main(String args[]) throws MyException{

try{

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print("请输入实数除法运算的被除数:");

String str = in.readLine();

double a = Double.parseDouble(str);

System.out.print("请输入除数:");

str = in.readLine();

double b = Double.parseDouble(str);

System.out.println("商结果:"+division(a,b));

}

catch(ArithmeticException e1){

System.out.println("商结果:Infinity"+e1);

26

System.out.println("商结果:NaN"+e1);

}

catch(NumberFormatException e2){

System.out.println("异常:字符串不能转换成整数!"+e2);

}

catch(IOException e3){

System.out.println("异常:IO异常"+e3);

}

finally{

System.out.println("程序结束!");

} } static double division(double a,double b)throws MyException{

if(a==100 && (b==4 || b==13))

throw new MyException("不符规范");

else return (a/b); } }

四、实验结果与分析(程序运行结果及其分析)

(1)

去掉Man类的public修饰, 程序运行不出来,提示缺少Man的公开方法。 (2)

(3)

(4)

27

(5)

(6)

(7)

(8)

(9)

(10)

28

(11)

五、实验体会(遇到问题及解决办法,编程后的心得体会)

学习程序设计的基本目的就是培养描述实际问题的程序化解决方案的关键技能Java面向对象程序设计是一门实践性比较强的课程在实际中我们必须把理论和实践结合起来。在实验中我们对照课本的知识然后进行实际的操作而后发现实际的运用比课本提到的要多很多理论总是来源于实践我们必须在现有的理论的基础上进行有效地实践。而这次实验也让我看到了现在学习的一个很大弱点就是实践的实践往往很少。在现实社会中我们必须懂得实际的操作才能更好的服务于社会。所以我必须在以后的学习中多动手多实际操作争取能在实践中找到属于自己新的感悟,终于在学习Java时达到了事半功倍的效果。

29

实验项目名称: 图形用户界面 实验学时: 6 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.5.9~17.5.23 实验成绩: 批改教师: 刘晶 批改时间:

30

实验3 图形用户界面

一、实验目的和要求

(1)掌握Swing组件的使用方法;

(2)熟练掌握Swing中常用布局管理器的使用方法; (3)掌握用户界面动作与事件的处理程序的编写方法; (4)熟练掌握构造用户界面的方法和常见界面元素的使用; (5)熟练掌握Java绘图的主要方法。

(6)调试程序要记录调试过程中出现的问题及解决办法;

(7)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;

(8) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。

三、实验过程

1. 计算器设计

2. 整数进制转换

将一个十进制整数分别转换成二进制、八进制和十六进制整数。

3. 模拟裁判评分。

设计如图所示图形界面,显示n个裁判的评分,根据制定规则计算出最后得分。要求:图形界面采用表格显示裁判评分,随裁判人数变化而变化;指定分数范围,若超出,则异常处理;

31

得分规则有指定接口约定,由多个接口对象给出多种得分规则,如求平均数值,或去掉一个最高分和一个最低分后,再求平均值。

4. 编译运行下例,然后修改程序,当使用鼠标单击后在另一位置重新绘制月亮。 【例】 在Applet中画月亮。 import java.awt.*; import java.applet.Applet; public class MoonApplet extends Applet { public void paint(Graphics g) //在Applet上绘图 { g.setColor(Color.red); g.drawString("The Moon",100,20); int x=0,y=0; //圆外切矩形左上角坐标 x = this.getWidth() /4; y = this.getHeight() /4; int diameter = Math.min(this.getWidth()/2, this.getHeight()/2); //圆的直径

g.setColor(Color.yellow); g.fillOval(x,y,diameter,diameter); //画圆

g.setColor(this.getBackground()); //设置为背景色 g.fillOval(x-20,y-20,diameter,diameter); //画圆 } } 5.根据阿基米德螺线的极坐标方程:r=aθ画出相应图形。

要求:

(1)注意选用适当的布局管理器设计图形用户界面,比较它们的布局情况;

(2)养成良好的编程习惯,严格按照命名规则为包、类及类成员命名,将每个程序打包,包的命名方式如three.num1表示实验三的第一题; (3)学会使用Eclipse的各种调试方法;

(4)学会查阅Java API文档,如查找事件类的处理里方法。

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。)

1.import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.*; import javax.swing.*;

32

public class Calulator implements ActionListener { JTextField t1; JPanel p1; JFrame f; static int count=1; static float value=0; int p2=0; String p; public Calulator() {f=new JFrame("Calulator"); f.setSize(400,200); p1=new JPanel(); t1=new JTextField(30); t1.setHorizontalAlignment(JTextField.RIGHT); p1.setLayout(new GridLayout(5,4)); f.add(t1); String str[]= {"开根","+","-","清零","7","8","9","/","4","5","6","*","1","2","3","负","0",".","正","="}; for(int i=0;i<20;i++) {JButton b=new JButton(str[i]); p1.add(b); b.addActionListener(this);} f.add(t1,BorderLayout.CENTER); f.add(p1,BorderLayout.SOUTH); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true);}

public void actionPerformed(ActionEvent e){ String c = e.getActionCommand(); if(c=="0"||c=="1"||c=="2"||c=="3"||c=="4"||c=="5"||c=="6"||c=="7"||c=="8"||c=="9"||c==".") {if(p2==0) {t1.setText(c);p2++;} else {t1.setText(t1.getText()+c); p2++;}} else if(p=="清零") {value=0;t1.setText(String.valueOf(value));} else {count++; p2=0; if(count==2 ) {p=c;value=Float.parseFloat(t1.getText());} if(c=="=") { if(p=="开根") {value=(float)Math.sqrt(Float.parseFloat(t1.getText())); t1.setText(String.valueOf(value));count-=2; } else if(p=="+"){value+=Float.parseFloat(t1.getText());count-=2; } else if(p=="-"){ value-=Float.parseFloat(t1.getText());count-=2; }

33

else if( p=="*"){value*=Float.parseFloat(t1.getText());count-=2;} else if(p=="/"){ value/=Float.parseFloat(t1.getText());count-=2;} else if (p==”正”) {value=Math.abs(Float.parseFloat(t1.getText())); t1.setText(String.valueOf(value)); count-=2;} else if(p=="负") {value=-1*Float.parseFloat(t1.getText()); t1.setText(String.valueOf(value));count-=2;} t1.setText(String.valueOf(value));value=0;}} } public static void main(String[] args) { new Calulator(); }}

2.import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ZhuanH extends JFrame implements ActionListener{ TextField t1,t2,t3,t4; public ZhuanH() {super("十进制整数转换"); this.setBackground(Color.BLUE); t1=new TextField(5); t2=new TextField(5); t3=new TextField(5); t4=new TextField(5); t1.setText(null); this.setSize(400,200); this.setLayout(new GridLayout(4,2)); this.add(new Label("十进制")); this.add(t1);t1.addActionListener(this); this.add(new Label("二进制")); this.add(t2); this.add(new Label("八进制")); this.add(t3); this.add(new Label("十六进制"));this.add(t4); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); }

public void actionPerformed(ActionEvent e){ String c = t1.getText(); t2.setText(Integer.toBinaryString(Integer.parseInt(c))); t3.setText(Integer.toOctalString(Integer.parseInt(c)));

34

t4.setText(Integer.toHexString(Integer.parseInt(c))); } public static void main(String[] args) { new ZhuanH(); }} 3.import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PingFen extends JFrame implements ActionListener{ JPanel p,p1; JTextField t; JTextField t1[]=new JTextField[10]; JButton b; float s=0,k; int t2,t3; public PingFen() { super("模拟裁判评分"); this.setSize(300,120); p1=new JPanel(new GridLayout(2,5)); this.add(p1,"North"); p=new JPanel(new FlowLayout(FlowLayout.RIGHT)); this.add(p,"South"); b=new JButton("平均分"); t=new JTextField(10); p.add(b);p.add(t); for(int i=0;i<10;i++) { t1[i]=new JTextField(6); t1[i].setText(null); p1.add(t1[i]); } b.addActionListener(this); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true);} public void actionPerformed(ActionEvent e) {float max,min; for(int i=0;i<10;i++) { try{ if(Float.parseFloat(t1[i].getText())>10.0) throw new Exception();

else continue;} catch(Exception ev) {JOptionPane.showMessageDialog(this,t1[i].getText()+"超出范围"+","+"

35

请重新输入"); t1[i].setText(null);} } max=Float.parseFloat(String.valueOf(t1[0].getText())); min=Float.parseFloat(String.valueOf(t1[0].getText())); for(int i=1;i<10;i++) { if((k=Float.parseFloat(String.valueOf(t1[i].getText())))>max){max=k;t2=i;} else if ((k=Float.parseFloat(String.valueOf(t1[i].getText())))new PingFen();}} 4. import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class MoonApplet extends Applet implements MouseListener { int x,y; public void init(){

x=this.getWidth()/4;

y=this.getHeight()/4;

addMouseListener(this); }

public void paint(Graphics g) //在Applet上绘图 { g.setColor(Color.red); g.drawString("The Moon",100,20); int diameter = Math.min(this.getWidth()/2, this.getHeight()/2); //圆的直径

g.setColor(Color.yellow); g.fillOval(x,y,diameter,diameter); //画圆

g.setColor(this.getBackground()); //设置为背景色 g.fillOval(x-20,y-20,diameter,diameter); //画圆 } public void mouseClicked(MouseEvent e){

36

x=e.getX(); y=e.getY(); repaint(); } 5. package package2; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LuoXuan extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; private LuoXuanCanvas canvas; //自定义画布组件 public LuoXuan() {super("阿基米德螺线"); Dimension dim=getToolkit().getScreenSize(); this.setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2); JPanel p=new JPanel(); this.add(p,"North"); JButton b=new JButton("选择颜色"); p.add(b); b.addActionListener(this); this.canvas=new LuoXuanCanvas(); this.getContentPane().add(this.canvas, "Center"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true);}

public void actionPerformed(ActionEvent e) {Color c=JColorChooser.showDialog(this, "选择颜色", Color.BLUE); this.canvas.setColor(c); this.canvas.repaint();}

public static void main(String[] args) {

new LuoXuan();} } class LuoXuanCanvas extends Canvas {private Color color; public void LuoXuan(Color color) {this.setColor(color);} public void setColor(Color color){this.color=color;} public void paint(Graphics g) {int x0=this.getWidth()/2; int y0 = this.getHeight()/2; g.setColor(this.color); g.drawLine(x0, 0, x0, y0*2); g.drawLine(0, y0, x0*2, y0);

37

for(int i=0;i<4000;i++) {double angle=i*Math.PI/512; double radius=angle*0.5; int x=(int)Math.round(radius*angle*Math.cos(angle)); int y=(int)Math.round(radius*angle*Math.sin(angle)); g.drawOval(x0+x, y0+y, 1, 1);} }}

四、实验结果与分析(程序运行结果及其分析)

(分析每题采用的布局管理器、事件处理类和主要功能实现方法) 1.

2.

3.

4.

38

5.

五、实验体会(遇到问题及解决办法,编程后的心得体会)

这次实验主要是对图形用户界面的设计,这里有鼠标触发的事件,就要让类实现MouseListener,在类里面实现MouseListener的方法,这里是选择单击时(mouseClicked()),这个方法,在方法体内用getX(),getY()方法来获取当前坐标。

39

实验项目名称:Java高级编程 实验学时: 4 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.5.30~17.6.6 实验成绩: 批改教师: 刘晶 批改时间:

40

实验4 Java高级编程

一、实验目的和要求

(1)了解文件的概念和文件对象的创建方法; (2)掌握使用文件输入输出流读写文件的方法; (3)了解线程的基本概念和多线程程序设计的基本方法; (4)掌握数据库连接的方法;

(5)创建SQL查询并更新数据库中的信息;

(6)调试程序要记录调试过程中出现的问题及解决办法;

(7)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;

(8) 做完实验后给出本实验的实验报告。

二、实验仪器和设备

奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件,MySQL数据库。

三、实验过程

(1)使用文件字节输入/输出流,合并两个指定文件;当文件中的数据已排序时,合并后的数据也要求是已排序的。

(2)将Java的关键字保存在一个文本文件中,判断一个字符串是否为Java的关键字。 (3)编写在构造方法中产生一个1-5之间的随机数的继承Thread类的线程类DelayPrintThread,使得线程体每休眠此随机数时间就打印输出线程号和休眠时间;另外编写应用DelayPrintThread类的Java应用程序TwoThread.java,在main()方法中创建两个线程,并应用sleep()控制主应用程序延迟一段时间。

(4)编写继承Runnable接口的Applet多线程小程序类MultiThreadApplet,编写继承该类的Applet小程序类Clock,在Clock中重新构造父类的run()方法,实现数字时钟的功能,要求不断刷新显示时、分、秒。

(5)为学生信息表stuinfo设计数据库应用程序,包括数据的输入、删除和查询功能。

要求:

(1)注意选用适当的文件流进行文件读写;

(2)学会两种创建线程的方法,并比较使用场合;

(3)养成良好的编程习惯,严格按照命名规则为包、类及类成员命名,将每个程序打包,包的命名方式如four.num1表示实验四的第一题; (4)学会查阅Java API文档,如查找常用工具类。

41

程序清单:

(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。) 1.import java.io.*; import java.util.Arrays; public class File { private String Filename; static int s=0,t=0; public File(String Filename) {this.Filename=Filename;} public void writeToFile(byte[] buffer) throws IOException {if(s==0) {FileOutputStream fout = new FileOutputStream(this.Filename); s++; Arrays.sort(buffer); fout.write(buffer); this.readFromFile(); fout.close(); } else { FileOutputStream fout1 = new FileOutputStream(this.Filename,true); Arrays.sort(buffer); fout1.write(buffer); fout1.close();} }

public void readFromFile() throws IOException { FileInputStream fin = new FileInputStream(this.Filename); if(t==0) {System.out.println("文件名"+":"+this.Filename+":");t++;} else System.out.println("合并两个文件后"+":"+this.Filename+":"); byte[] buffer = new byte[512]; int count = fin.read(buffer); while (count!=-1) { for (int i=0; i42

byte[] buffer = {0,1,4,3,2,5,6,9,8,7}; byte[] buffer1 = {10,11,12,14,15,17,16,19,20,13,18}; File afile = new File("ByteFile.dat"); afile.writeToFile(buffer); afile.writeToFile(buffer1); afile.readFromFile();} } 2.import java.io.*; public class File { private String Filename; public File(String Filename) {this.Filename=Filename;} public void writerLine(String[] s) throws IOException {FileWriter f = new FileWriter(this.Filename); System.out.println(this.Filename+"文件中的java关键字有"+":"); for(int i=0;ipublic void Text(String[] s,String[] s1) {int i,j; for(i=0;iif(s1[i]==s[j])

{System.out.println(s1[i]+"是java中的关键字");break;}

else continue; if(j==s.length)System.out.println(s1[i]+"不是java中的关键字");} } public static void main(String[] args) throws IOException { String[]s={"public","class","static","void","String","print","byte","boolean","int","short","long","throw","cath","continue","private","abstract","Interface","Exception"}; String[] s1={"pblic","class","string"}; File a=new File("myfile.dat"); a.writerLine(s); a.Text(s,s1); } } 3. public class DelayPrintThread extends Thread{ private int number,time; public DelayPrintThread(int number)

{this.number=number;

43

time=(int)(Math.random()*5); } public void run(){ try { Thread.sleep(this.time); } catch (InterruptedException e) {} System.out.println("线程"+this.number+":"+"休眠时间"+this.time); } public class TwoThread {

public static void main(String[] args) {

DelayPrintThread a=new DelayPrintThread(1); DelayPrintThread b=new DelayPrintThread(2); a.start(); b.start();} } 4.import java.applet.Applet; import java.awt.*; import java.util.Date; import java.text.SimpleDateFormat; public class MultiThreadApplet extends Applet implements Runnable { Thread a; public void start(){ if(a==null) {a=new Thread(this);

a.start();}

} public void stop(){ if(a!=null){ a.stop();

a=null;} } public void run(){} public void paint(Graphics g) {SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日E a hh时 mm分ss秒"); g.drawString(sdf.format(new Date()),50,100);} }

44

public class Clock extends MultiThreadApplet{ public void run(){

repaint(); try{a.sleep(1000);} catch (InterruptedException e) {} }} 5.import java.sql.*; public class Statement{ public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn=DriverManager.getConnection("jdbc:odbc:student"); Statement stmt=conn.createStatement(); String Sql="SELECT stu_id,stu_name,city FROM student WHERE stu_id=5"; String Sql="INSERT INTO student(stu_id,stu_name,city) VALUES('5','小红','徐州')"; String Sql="DELETE FROM student WHERE stu_id=5"; int count=stmt.executeUpdate(Sql); System.out.println("插入"+count+"行"); ResultSet rs=stmt.executeQuery(Sql); if(rs.next()) {System.out.println( "行"+rs.getRow()+":"+rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)); } else System.out.println("没有数据"); count=stmt.executeUpdate(Sql); rs=stmt.executeQuery(Sql); if(rs.next()) {System.out.println("行"+rs.getRow()+":"+rs.getString(1)+","+rs.getString(2)+","+rs.getString(5)); } else System.out.println("没有数据"); } }

四、实验结果与分析(程序运行结果及其分析) 1.

45

2.

3.

4.

五、实验体会(遇到问题及解决办法,编程后的心得体会)

通过这次实验,我基本能够理解线程的运行了,学会调用Thread类中的系统函数以及掌握这些函数的作用是难点,start()是开辟一条新线程。子类重写父类的run()方法,里面用sleep,来控制每个线程的休眠时间,但是得注意这里应该要用try-catch语句来捕获中断异常。

46

java实验报告2013_java实验报告4相关推荐

  1. 20155328 《Java程序设计》 实验二(Java面向对象程序设计) 实验报告

    20155328 <Java程序设计> 实验二(Java面向对象程序设计) 实验报告 单元测试 一.单元测试和TDD 编程时需理清思路,将编程需求等想好,再开始编.此部分可用伪代码实现. ...

  2. java数组实验报告_Java实验一实验报告

    实验内容 1.使用JDK编译.运行简单的Java程序: 2.使用Eclipse编辑.编译.运行.调试Java程序. 实验要求 1.没有Linux基础的同学建议先学习<><>课程 ...

  3. java类与对象实验_JAVA类与对象实验报告

    <JAVA类与对象实验报告>由会员分享,可在线阅读,更多相关<JAVA类与对象实验报告(6页珍藏版)>请在人人文库网上搜索. 1.面向对象程序设计实验报告实验三.类与对象(1) ...

  4. java实验七实验报告_Java实验报告-7-风扇

    Java实验报告 实验题目实验七综合实验风扇 代码: import java.awt.Col or; import java.awt.Graphics; import java.awt.event.A ...

  5. java实验册_Java实验报告册Java实验报告册.doc

    Java实验报告册Java实验报告册 <面向对象程序设计> 实验报告与习题册2013 / 2014 学年 第1学期系 别 计算机科学与技术系专 业 班 级 姓 名 指导教师 目 录 项 目 ...

  6. bit java实验2_2018-2019-2 20175120 实验五《Java网络编程》实验报告

    实验报告封面 课程:Java程序设计 班级:1751班 姓名:彭宇辰 学号:20175120 指导教师:娄嘉鹏 实验日期:2019年5月26日 实验时间:13:10 - 15:25 实验序号:20 实 ...

  7. 20155201 实验四《Java面向对象程序设计》实验报告

    20155201 实验四<Java面向对象程序设计>实验报告 一.实验内容 1.基于Android Studio开发简单的Android应用并部署测试; 2.了解Android.组件.布局 ...

  8. java构成对象的三要素_20155237 《JAVA程序设计》实验二(JAVA面向对象程序设计)实验报告...

    20155237 <JAVA程序设计>实验二(JAVA面向对象程序设计)实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S ...

  9. 2018-2019-2 20175230 实验三《Java面向对象程序设计》实验报告

    目录 实验三 实验三 敏捷开发与XP实践 实验内容 实验要求 实验步骤 (一) 编码标准 (二)敏捷开发与XP (三)敏捷开发与XP 实验体会 实验三 实验三 敏捷开发与XP实践 实验内容 1.XP基 ...

最新文章

  1. 【原创】Linux环境下的图形系统和AMD R600显卡编程(11)——R600指令集
  2. StringBuilder、StringBuffer、String区别
  3. Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例
  4. oracle数据恢复方法
  5. 常用linux下网络相关命令
  6. hdu 3987(最小割的边数)
  7. 【SpringBoot】【Thyemeleaf 】【Spring EL表达式】 SPEL调用静态类、静态方法
  8. scala创建并使用Enumerations
  9. 修改GIT的user.name和user.email
  10. 我的Dojo中有一个Mojo(如何编写Maven插件)
  11. U盘的RUNAUTO..文件的删除
  12. JS module的导出和导入 1
  13. Spring和Mybatis整合-mapper开发
  14. 【UCOSIII操作系统】软件定时器篇
  15. 四川中小学计算机能力提升,四川省中小学教师信息技术应用能力提升工程2.0
  16. 自主安装IPA文件到iPhone上
  17. sybase 字符串转数字_sybase字符串转日期
  18. 机器学习sklearn-线性回归
  19. Android studio MacBook快捷键
  20. oracle 审计 分区表,oracle分区表的分类及测试

热门文章

  1. Java魔法堂:自定义和解析注解
  2. 【干货】前端工程与性能优化
  3. Oracle 11g RAC 修改IP
  4. 清华大学MBA在职班第一学年第二学期课表
  5. 【重点!DP】LeetCode 97. Interleaving String
  6. 【To Do】程序员面试金典——18.11最大子方阵
  7. linux 权限rwx(4,2,1)详细说明
  8. 【Spark】快速简介
  9. 论文写作--表格解读
  10. 4.XXE (XML External Entity Injection)