Java实验报告电子稿(汇编)

第一篇:Java实验报告电子稿
课程名称:
学生学号:学生姓名:
所属院部:指导教师:
学生实验报告
(理工类)
JAVA程序设计专业班级: 15——20 16学年第2学期
金陵科技学院教务处制 实验项目名称:JAVA编程基础实验学时: 4 同组学生姓名:————实验地点:1514 实验日期:2016.4.11实验成绩: 批改教师:批改时间:
一、实验目的和要求
(1)熟练掌握JDK1.7及Eclipse Kepler Service Release 1(下简称Eclipse)编写调试Java应用程序及Java小程序的方法;(2)熟练掌握Java应用程序的结构;
(3)了解Java语言的特点,基本语句、运算符及表达式的使用方法;(4)熟练掌握常见数据类型的使用;
(5)熟练掌握if-else、switch、while、do-while、for、continue、break、return语句的使用方法;
(6)熟练掌握数组和字符串的使用;
(7)调试程序要记录调试过程中出现的问题及解决办法;
(8)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;
(9)做完实验后给出本实验的实验报告。
二、实验仪器和设备
奔腾以上计算机,Windows 操作系统,装有JDK1.7和Eclipse软件。
三、实验过程
(1)分别使用JDK命令行和Eclipse编译运行Java应用程序。记录操作过程。Java应用程序参考如下:
思考:1.适当添加注释信息,通过javadoc生成注释文档;
2.为主方法传递参数“Hello world”字符串,并输出; 3.压缩生成“.jar”文件。(2)分别使用JDK命令行和Eclipse编译Java Applet,并建立HTML文档运行该Applet。记录操作过程。
Java小应用程序参考如下:
HTML文档参考如下: (3)输出下列数字形式。①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(4)采用数组输出等腰三角形的杨辉三角。(5)判断回文字符串
回文是一种“从前向后读”和“从后向前读”都相同的字符串。如“rotor”是一个回文字符串。
程序中使用了两种算法来判断回文字符串:
算法一:分别从前向后和从后向前依次获得原串str的一个字符ch1、ch2,比较ch1和ch2,如果不相等,则str肯定不是回文串,yes=false,立即退出循环:否则继续比较,直到字符全部比较完,yes的值仍为true,才能肯定str是回文串。
算法二:将原串str反转成temp串,再比较两串,如果相等则是因文字符串。
要求:
(1)编译调试程序之前应配置好环境变量;
(2)要分别掌握用JDK命令行和Eclipse集成开发环境调试Java程序;(3)注意Java两大类程序:应用程序和小程序的区别。
程序清单:
(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。)
(实验三程序清单)1.package test1;public class Ex3_1 { public static void main(String[] args){ for(int i = 0;i < 4;i++)
} } 2.package test1;public class Ex3_2 {
public static void main(String[] args){ for(int i = 0;i < 4;i++){ {
for(int j = 0;j < 4;j++)
if(i <= j)System.out.print(i + “ ”);else System.out.print(j + “ ”);System.out.println();} for(int j = 0;j < 4i * 2);k++)System.out.print(“ ”);a[j] = a[j1;i < str.length()c2.real, c1.imborderA)*(pborderC));}
publicstaticvoid main(String[] args){
Ex2 test = new Ex2(6, 8, 10);
System.out.println(“The girth of the triangle is ” + test.calGirth());
System.out.println(“The square of the triangle is ” + test.calSquare());} }(实验二程序3)1.package mypackage;
publicclass Calculator { publicdouble add(double num1, double num2){ return num1 + num2;} publicdouble minus(double num1, double num2){ return num11);text.setText(str);if(str == “"){ text.setText(”0.“);first = true;} return;} if(current.charAt(0)>= '0'&¤t.charAt(0)<= '9'||current == ”.“){ if(first){ text.setText(”“);first = false;} text.setText(text.getText()+ current);} else { System.out.print(”“ + value + op + text.getText()+ ”=“);switch(op){ case '+':
value += Float.parseFloat(text.getText());
break;case '-':
value-= Float.parseFloat(text.getText());
break;
case '*':
value *= Float.parseFloat(text.getText());
break;case '/':
value /= Float.parseFloat(text.getText());
break;} System.out.println(”“ + value);text.setText(”“ + value);op = current.charAt(0);first = true;} } public static void main(String arg[]){ new Ex1();} }
(实验三程序2)
package test3;import java.awt.*;import java.awt.event.*;import javax.swing.*;@SuppressWarnings(”serial“)public class Ex2 extends JFrame implements ActionListener { private JTextField texts[], text_score;private JButton button;private Average av;public Ex2(int rows, int columns, Average av){ super(”模拟裁判评分“);this.setBounds(300, 240, 400, 150);this.setBackground(Color.lightGray);this.setDefaultCloseOperation(EXIT_ON_CLOSE);JPanel panel1 = new JPanel(new GridLayout(rows, columns));this.getContentPane().add(panel1);texts = new JTextField[rows * columns];int a=texts.length;for(int i = 1;i < a+1;i++){ texts[i-1] = new JTextField(i + ”.0“, 6);texts[i-1].setHorizontalAlignment(JTextField.CENTER);panel1.add(texts[i-1]);} JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));this.getContentPane().add(panel2, ”South“);button = new JButton(”平均分“);panel2.add(button);button.addActionListener(this);text_score = new JTextField(”“, 10);text_score.setEditable(false);text_score.setHorizontalAlignment(JTextField.CENTER);panel2.add(text_score);this.setVisible(true);this.av = av;} public void actionPerformed(ActionEvent e){ double table[] = new double[texts.length];for(int i = 0;i < texts.length;i++)try { table[i] = Double.parseDouble(texts[i].getText());if(table[i] > 10)throw new Exception(”NumException“);} catch(NumberFormatException nfe){ JOptionPane.showMessageDialog(this, texts[i].getText()+ ”字符串不能转换符点数请重新输入。“);} catch(Exception ex){ if(ex.getMessage()== ”NumException“)JOptionPane.showMessageDialog(this, table[i] + ”分数范围超出请重新输入“);} text_score.setText(String.format(”%1.2f“, av.average(table)));} public static void main(String arg[]){ new Ex2(2, 5, new AverageExceptMaxMin());} } class AverageExceptMaxMin implements Average { public double average(double table[]){ if(table!= null && table.length > 2){ double sum = table[0], max = table[0], min = table[0];for(int i = 1;i < table.length;i++){ sum += table[i];if(table[i] > max)max = table[i];if(table[i] < min)min = table[i];} return(summin)/(table.length-2);} return 0.0;} }(实验三程序3)
package test3;import java.awt.*;import java.awt.event.*;
importjavax.swing.JFrame;@SuppressWarnings(”serial“)class Mycanvas extends Canvas implements MouseListener,WindowListener { int x=0,y=0;Mycanvas(){ setSize(400,400);setBackground(Color.lightGray);addMouseListener(this);} public void paint(Graphics g){ 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 mousePressed(MouseEvent e){ x=e.getX();y=e.getY();repaint();} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){ x=e.getX();y=e.getY();repaint();} public void update(Graphics g){ paint(g);super.update(g);} public void windowActivated(WindowEvent e){
// TODO Auto-generated method stub
} public void windowClosed(WindowEvent e){
// TODO Auto-generated method stub
System.exit(0);} public void windowClosing(WindowEvent e){
// TODO Auto-generated method stub
System.exit(0);} public void windowDeactivated(WindowEvent e){
// TODO Auto-generated method stub
} public void windowDeiconified(WindowEvent e){
// TODO Auto-generated method stub
} public void windowIconified(WindowEvent e){
// TODO Auto-generated method stub
} public void windowOpened(WindowEvent e){
// TODO Auto-generated method stub
} } public class Ex3 { public static void main(String args[]){ JFrame f=new JFrame();f.setBounds(500,300,400,400);f.setVisible(true);f.add(new Mycanvas());f.validate();} } package test3;publicinterface Average { double average(double[] table);}(实验三程序4)
package test3;import java.awt.*;import java.awt.event.*;import javax.swing.*;@SuppressWarnings(”serial“)public class Ex4 extends JFrame implements ActionListener { private ArchimedesCanvas archimedes;private JRadioButton radiob_color[];public Ex4(){ super(”阿基米德螺线“);Dimension dim = getToolkit().getScreenSize();this.setBounds(dim.width / 4, dim.height / 4, dim.width / 2, dim.height / 2);this.setDefaultCloseOperation(EXIT_ON_CLOSE);JToolBar toolbar = new JToolBar();this.getContentPane().add(toolbar, ”North“);String colorstr[] = { ”红“, ”绿“, ”蓝“ };ButtonGroup bgroup_color = new ButtonGroup();radiob_color = new JRadioButton[colorstr.length];for(int i = 0;i < radiob_color.length;i++){ radiob_color[i] = new JRadioButton(colorstr[i]);radiob_color[i].addActionListener(this);bgroup_color.add(radiob_color[i]);toolbar.add(radiob_color[i]);} radiob_color[0].setSelected(true);archimedes = new ArchimedesCanvas(Color.red);this.getContentPane().add(archimedes, ”Center“);this.setVisible(true);} public void actionPerformed(ActionEvent e){ Color c = null;if(e.getSource()== radiob_color[0])c = new Color(255, 0, 0);if(e.getSource()== radiob_color[1]){ c = new Color(0, 255, 0);} if(e.getSource()== radiob_color[2])c = new Color(0, 0, 255);archimedes.setColor(c);archimedes.repaint();} public static void main(String[] args){ new Ex4();} } @SuppressWarnings(”serial“)class ArchimedesCanvas extends Canvas implements ComponentListener, FocusListener, ActionListener { private Color color;private Timer mTimer;public ArchimedesCanvas(Color color){ this.setBackground(Color.WHITE);this.setColor(color);this.addComponentListener(this);this.addFocusListener(this);} 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(color);g.drawLine(x0, 0, x0, y0 * 2);g.drawLine(0, y0, x0 * 2, y0);for(int i = 0;i < 4000;i++){ double angle = i * Math.PI / 512;double radius = 0.5 * angle;int x =(int)Math.round(radius * angle * Math.cos(angle));int y =(int)Math.round(radius * angle * Math.sin(angle));mTimer = new Timer(1000, this);mTimer.start();g.drawOval(x0 + x, y0 + y, 1, 1);} } public void componentMoved(ComponentEvent e){} public void componentHidden(ComponentEvent e){} public void componentResized(ComponentEvent e){ this.repaint();} public void componentShown(ComponentEvent e){} public void focusGained(FocusEvent arg0){ mTimer.stop();} public void focusLost(FocusEvent arg0){ mTimer.restart();} public void actionPerformed(FocusEvent arg0){} public void actionPerformed(ActionEvent e){} }
四、实验结果与分析 1.2.3.4.实验项目名称: Java高级编程实验学时: 6 同组学生姓名:————实验地点: 实验日期:实验成绩: 批改教师:批改时间:
一、实验目的和要求(1)了解文件的概念和文件对象的创建方法;(2)掌握使用文件输入输出流读写文件的方法;(3)了解线程的基本概念和多线程程序设计的基本方法;(4)掌握数据库连接的方法;
(5)创建SQL查询并更新数据库中的信息;
(6)调试程序要记录调试过程中出现的问题及解决办法;
(7)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;
(8)做完实验后给出本实验的实验报告。
二、实验仪器和设备
奔腾以上计算机,Windows 操作系统,装有JDK1.7和Eclipse软件,Access数据库。
三、实验过程
(1)使用文件字节输入/输出流,合并两个指定文件;当文件中的数据已排序时,合并后的数据也要求是已排序的。
(2)将Java的关键字保存在一个文本文件中,判断一个字符串是否为Java的关键字。(3)编写在构造方法中产生一个1-5之间的随机数的继承Thread类的线程类DelayPrintThread,使得线程体每休眠此随机数时间就打印输出线程号和休眠时间;另外编写应用DelayPrintThread类的Java应用程序TwoThread.java,在main()方法中创建两个线程,并应用sleep()控制主应用程序延迟一段时间。
(4)编写继承Runnable接口的Applet多线程小程序类MultiThreadApplet,编写继承该类的Applet小程序类Clock,在Clock中重新构造父类的run()方法,实现数字时钟的功能,要求不断刷新显示时、分、秒。
要求:
(1)注意选用适当的文件流进行文件读写;
(2)学会两种创建线程的方法,并比较使用场合;
(3)养成良好的编程习惯,严格按照命名规则为包、类及类成员命名,将每个程序打包,包的命名方式如four.num1表示实验四的第一题;(4)学会查阅Java API文档,如查找常用工具类。
程序清单:
(建议程序中适当添加注释信息,增强可读性;较长程序可分栏书写,保证报告排版整洁美观。)
(实验四程序清单续1)实验1: package test4;import java.io.*;publicclass Ex1{ public static void main(String[]args)throws IOException{
BufferedReader f1=new BufferedReader(new
FileReader(”d:array1.txt“));
BufferedReader f2=new BufferedReader(new
FileReader(”d:array2.txt“));
BufferedWriter f=new BufferedWriter(new
FileWriter(”d:result.txt“));
String s1=f1.readLine();
String s2=f2.readLine();
System.out.println(s1);
System.out.println(s2);
char[]c1=s1.toCharArray();
char[]c2=s2.toCharArray();
char[]c=new char[c1.length+c2.length];
System.arraycopy(c1,0,c,0,c1.length);
System.arraycopy(c2,0,c,c1.length,c2.length);
System.out.println(c);
Sort(c);
f.write(c);
f.flush();
f.close();
f1.close();
f2.close();} public static void Sort(char[]values){//冒泡倒序排序法
chartemp;
for(int i=0;i for(int j=0;j if(values[j]>values[j+1]){ temp=values[j]; values[j]=values[j+1]; values[j+1]=temp; } } } } } 实验2: package test4;import java.io.*;importjava.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;public class Ex2 { public static void main(String[] args)throws IOException { boolean isHotKey = doCheck(”class“); if(isHotKey){ System.out.println(”yes“); } else { System.out.println(”no“); } } private static boolean doCheck(String input)throws IOException { boolean isHotKey = false;File file = new File(”D:/javahotkey.txt“);//写入关键字 FileWriter fout=new FileWriter(file);fout.write(”abstract assert class“);fout.close();String content = ”“;FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);String temp;while(null!=(temp = br.readLine())){ content += temp;} System.out.println(”The content of text is :“);System.out.println(content);System.out.println(”The result is :“);isHotKey = content.contains(input);//检查keyList中是否包含input返回boolean类型数值 return isHotKey;} } (实验四程序清单续2) 实验3: package test4;public class Ex3 { public static void main(String args[])throws InterruptedException { DelayPrintThread thread1 = new DelayPrintThread(); DelayPrintThread thread2 = new DelayPrintThread(); thread1.start(); thread2.start();} } class DelayPrintThread extends Thread { int sleepTime;public DelayPrintThread(){ sleepTime = 1 +(int)(Math.random()* 5);// 产生1~5之间的随机数 } public void run(){ while(true){ try { Thread.sleep(sleepTime);System.out.println(”the id of thread is:“+Thread.currentThread().getId());System.out.println(”the sleep time is:“+sleepTime);} catch(InterruptedException e){ // TODO Auto-generated catch block break;} } } } 实验4: package test4;import java.awt.*;//用于导入必要的javaBean文件 import java.applet.*;import java.util.Calendar;import java.util.GregorianCalendar;@SuppressWarnings(”serial“)public class Ex4 extends MultiThreadApplet { Thread clockThread;Font font;public void init()//用于初始化的标准程序 { font = new Font(”TimesRoman“, Font.BOLD, 48);//定义一字体格式字体timesRoman 加粗大小48磅 } public void start()//用于启动的标准程序 { if(clockThread == null)//判断线程是否还未创建 clockThread = new Thread(this, ”Showtime“);//将本程序创建成名为showtime的新线程 clockThread.start();//启动线程 } public void run()// 用于定义运行内容的标准程序 { // while(clockThread!=null) while(true)// 此循环让时钟始终走下去 { repaint();// 重绘组件即调用paint方法画出下一个新时钟 try { Thread.sleep(1000);// 休眠1秒即让时钟一秒走一次 } catch(InterruptedException e)// 异常错误处理防止出现中断错误 { } } } public void paint(Graphics g)// 用于绘画的标准程序此处画出当前时间的表盘 { Calendar calendar =new GregorianCalendar();// g.drawString(calendar.get(Calendar.HOUR_OF_DAY)+ ”:“ + calendar.get(Calendar.MINUTE)+ ”:“ + calendar.get(Calendar.SECOND), 10, 100);// 在时钟的下方用文字显示当前的时间 } public void stop(){ //用于停止的标准程序 clockThread.interrupt();//将时钟线程停止 } } @SuppressWarnings(”serial")class MultiThreadApplet extends Applet implements Runnable { public void run(){ // TODO Auto-generated method stub } } 四、实验结果与分析 实验1: Array1:13579 array2:2468 合并后 result:123456789 实验2: The content of text is : abstract assert class The result is : yes 实验3: the sleep time is:1 the id of thread is:9 the sleep time is:1 the id of thread is:9 the sleep time is:1 the id of thread is:10 the sleep time is:4 the id of thread is:9 the sleep time is:1 实验4: 左侧为时间 学 生 实 验 报 告 册 (理工类) 课程名称:面向对象程序设计 专业班级:16计算机科学与技术(专转本) 学生学号: 1613203022 学生姓名: 张义丹 所属院部: 计算机工程 指导教师: 刘 晶 16 ——20 17 学年 第 2 学期 金陵科技学院教务处制 实验报告书写要求 实验报告上交电子稿,标题采用四号黑体,正文采用小四号宋体,单倍行距。 实验报告书写说明 实验报告中实验目的和要求、实验仪器和设备、实验内容与过程、实验结果与分析这四项内容为必需项。教师可根据学科特点和实验具体要求增加项目。 填写注意事项 (1)细致观察,及时、准确、如实记录。(2)准确说明,层次清晰。 (3)尽量采用专用术语来说明事物。 (4)外文、符号、公式要准确,应使用统一规定的名词和符号。(5)应独立完成实验报告的书写,严禁抄袭、复印,一经发现,以零分论处。 实验报告批改说明 实验报告的批改要及时、认真、仔细,一律用红色笔批改。实验报告的批改成绩采用五级记分制或百分制,按《金陵科技学院课堂教学实施细则》中作业批阅成绩评定要求执行。 实验项目名称:Java编程基础 实验学时: 6 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.3.21~17.4.4 实验成绩: 批改教师: 刘晶 批改时间: 实验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);} } (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); System.out.println(“s1 == s4= ” +result142); System.out.println(“s1 equals s5= ” +result151); System.out.println(“s1 == s5= ” +result152);} }(8)判断回文字符串 回文是一种“从前向后读”和“从后向前读”都相同的字符串。如“rotor”是一个回文字符串。 程序中使用了两种算法来判断回文字符串: 算法一:分别从前向后和从后向前依次获得原串str的一个字符ch1、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;} 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] + “ ”);// 打印数据 } } } 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;i arr[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(); } } } ②public class Shuzu { public static void main(String args[]){ int num[][]=new int[4][];for(int i=0;i num[i]=new int[2*i+1]; for(int m=0;m System.out.print(“ ”); } int k=i+1; for(int j=0;j if(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;j System.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;j 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”}; 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) (2) (3) (4) (5) (6) (7) (8) (9) 五、实验体会(遇到问题及解决办法,编程后的心得体会) 在这次实验中,我知道了eclipse和jdk运行程序的区别,jdk比较麻烦一些,需要配置变量。在实验中,配置jdk的环境变量要注意它的path和 classpath,如果classpath本身就有,可以在后面加分号,这样不影响其它的classpath的使用。学会了如何生成注释文档,主函数传递参数的方法,还有压缩文件,实验中还对数组的创建和使用进行了练习,还有一些类的应用。 实验项目名称: 面向对象编程 实验学时: 8 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.4.11~17.5.2 实验成绩: 批改教师: 刘晶 批改时间: 实验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)设计复数类,成员变量包括实部和虚部,成员方法包括实现复数加法、减法、字符串描述、比较是否相等等操作。 (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){ 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有关的异常(空白处补全捕获语句) //捕获数值转化时的异常,如不能将字符转化成数值 //捕获除数为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) {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);//创建类,调用类里面的方法 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) {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);} 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; 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; 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()); 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); 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();//键盘输入 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(”商结果:“+pision(a,b)); } catch(ArithmeticException e1){ System.out.println(”商结果:Infinity“+e1); 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 pision(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) (5) (6) (7) (8) (9) (10) (11) 五、实验体会(遇到问题及解决办法,编程后的心得体会) 学习程序设计的基本目的就是培养描述实际问题的程序化解决方案的关键技能Java面向对象程序设计是一门实践性比较强的课程在实际中我们必须把理论和实践结合起来。在实验中我们对照课本的知识然后进行实际的操作而后发现实际的运用比课本提到的要多很多理论总是来源于实践我们必须在现有的理论的基础上进行有效地实践。而这次实验也让我看到了现在学习的一个很大弱点就是实践的实践往往很少。在现实社会中我们必须懂得实际的操作才能更好的服务于社会。所以我必须在以后的学习中多动手多实际操作争取能在实践中找到属于自己新的感悟,终于在学习Java时达到了事半功倍的效果。 实验项目名称: 图形用户界面 实验学时: 6 同组学生姓名: ———— 实验地点: 工科楼A101 实验日期: 17.5.9~17.5.23 实验成绩: 批改教师: 刘晶 批改时间: 实验3 图形用户界面 一、实验目的和要求 (1)掌握Swing组件的使用方法; (2)熟练掌握Swing中常用布局管理器的使用方法;(3)掌握用户界面动作与事件的处理程序的编写方法;(4)熟练掌握构造用户界面的方法和常见界面元素的使用;(5)熟练掌握Java绘图的主要方法。 (6)调试程序要记录调试过程中出现的问题及解决办法; (7)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验; (8)做完实验后给出本实验的实验报告。 二、实验仪器和设备 奔腾以上计算机,Windows 操作系统,装有JDK1.6和Eclipse4.2软件。 三、实验过程 1.计算器设计 2.整数进制转换 将一个十进制整数分别转换成二进制、八进制和十六进制整数。 3.模拟裁判评分。 设计如图所示图形界面,显示n个裁判的评分,根据制定规则计算出最后得分。要求:图形界面采用表格显示裁判评分,随裁判人数变化而变化;指定分数范围,若超出,则异常处理; 得分规则有指定接口约定,由多个接口对象给出多种得分规则,如求平均数值,或去掉一个最高分和一个最低分后,再求平均值。 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.*; 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;} 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))); 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()+”超出范围“+”,“+” 请重新输入“);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){ 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); 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()方法来获取当前坐标。 实验项目名称:Java高级编程 实验学时: 4 同组学生姓名: ———— 实验地点第二篇:JAVA实验报告
Java实验报告电子稿(汇编)
本文2025-01-29 04:28:27发表“合同范文”栏目。
本文链接:https://www.wnwk.com/article/314969.html
- 二年级数学下册其中检测卷二年级数学下册其中检测卷附答案#期中测试卷.pdf
- 二年级数学下册期末质检卷(苏教版)二年级数学下册期末质检卷(苏教版)#期末复习 #期末测试卷 #二年级数学 #二年级数学下册#关注我持续更新小学知识.pdf
- 二年级数学下册期末混合运算专项练习二年级数学下册期末混合运算专项练习#二年级#二年级数学下册#关注我持续更新小学知识 #知识分享 #家长收藏孩子受益.pdf
- 二年级数学下册年月日三类周期问题解题方法二年级数学下册年月日三类周期问题解题方法#二年级#二年级数学下册#知识分享 #关注我持续更新小学知识 #家长收藏孩子受益.pdf
- 二年级数学下册解决问题专项训练二年级数学下册解决问题专项训练#专项训练#解决问题#二年级#二年级数学下册#知识分享.pdf
- 二年级数学下册还原问题二年级数学下册还原问题#二年级#二年级数学#关注我持续更新小学知识 #知识分享 #家长收藏孩子受益.pdf
- 二年级数学下册第六单元考试卷家长打印出来给孩子测试测试争取拿到高分!#小学二年级试卷分享 #二年级第六单考试数学 #第六单考试#二年级数学下册.pdf
- 二年级数学下册必背顺口溜口诀汇总二年级数学下册必背顺口溜口诀汇总#二年级#二年级数学下册 #知识分享 #家长收藏孩子受益 #关注我持续更新小学知识.pdf
- 二年级数学下册《重点难点思维题》两大问题解决技巧和方法巧算星期几解决周期问题还原问题强化思维训练老师精心整理家长可以打印出来给孩子练习#家长收藏孩子受益 #学霸秘籍 #思维训练 #二年级 #知识点总结.pdf
- 二年级数学下册 必背公式大全寒假提前背一背开学更轻松#二年级 #二年级数学 #二年级数学下册 #寒假充电计划 #公式.pdf


