java上机实验答案与解析

更新时间:2024-04-17 08:24:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

JAVA上机实验题答案与解析

实验一 Java程序编程

1.编写一个Java应用程序,输出内容为Hello!。

注:文件位置位于e:\\2:\\Hello.java 编译:(1)e:(2)cd 2 (3)javac Hello.java(4)java Hello 2.编写一个Java小应用程序,输出内容为我一边听音乐,一边学Java。 第一步编写

import java.awt.*; import java.applet.*;

public class MyApplet extends Applet{ public void paint(Graphics g){

g.drawString(\我一边听音乐,我一边做java\ } }

第二步 在DOS环境中编译(....javac MyApplet.java) 第三步 使用记事本编写

第四步 将记事本文件名命名为MyApplet.html 第五步 打开MyApplet.html

实验二 类的定义

1.编写Java应用程序,自定义Point类,类中有两个描述坐标位置的double变量x,y,利用构造方法,实现对Point 对象p1,p2初始化,p1和p2对应坐标分别为(15,20),(10,30);定义方法getX(),getY()分别获得点的横坐标和纵坐标;定义方法setX(),setY()分别获得点的横坐标和纵坐标;并且把p1和p2输出; public class Point { double x,y; Point(double x,double y){ this.x=x; this.y=y; } double getX(){ return x; } double getY(){

return y; } void setX(double x){ this.x=x; } void setY(double y){ this.y=y; } public static void main(String[] args) { Point p1=new Point(15,20);//初始化 Point p2=new Point(10,30); System.out.println(\横坐标为\ 纵坐标为\ System.out.println(\横坐标为\ 纵坐标为 \ } }

运行结果:横坐标为15.0 纵坐标为20.0 横坐标为10.0 纵坐标为 30.0

2.编写Java应用程序,自定义Circle类,类中有两个double 变量r,s,一个类变量pi,利用构造方法实现对半径是3和5.5的初始化,自定义getArea方法实现圆面积求解; public class Circle { double s,r; static double pi=3.14159265; public Circle(double r){ this.r=r; } double getArea(){ this.s=pi*r*r; return s; } public static void main(String[] args) { Circle c1=new Circle(3); Circle c2=new Circle(5.5); System.out.println(c1.getArea ()); System.out.println(c2.getArea()); } }

实验三 类的继承和多态性

1.(1)编写一个接口ShapePara,要求: 接口中的方法: int getArea():获得图形的面积。int getCircumference():获得图形的周长 (2)编写一个圆类Circle,要求:圆类Circle实现接口ShapePara。 该类包含有成员变量: radius:public 修饰的double类型radius,表示圆的半径。 x:private修饰的double型变量x,表示圆心的横坐标。 y:protected修饰的double型变量y,表示圆心的纵坐标。 包含的方法有: Circle(double radius) 有参构造方法。以形参表中的参数初始化半径,圆心为坐标原点。 double getRadius():获取半径为方法的返回值。void setCenter(double x, double y):利用形参表中的参数设置类Circle的圆心坐标。void setRadius(double radius):利用形参表中的参数设置类Circle的radius域。 在主方法中产生半径为5的圆。 interface ShapePara { double getArea(double r); double getCircumference(double r);

}//注: Circle是在接口中建立的calss,即先建立接口,在建立接口的类 class Circle implements ShapePara{ private double x; protected double y; public double r; Circle(double r){ this.r=r; } void setRadius(double r){ this.r=r; } double getRadius(){ return r; } double getArea(){

return (3.14*r*r); } double getCircumference(){ return 3.14*2*r; } void setCenter(double x,double y){ this.x=x; this.y=y; } double getCenterx(){ return x; } double getCentery(){ return y; } }

public class A { public static void main(String[] args) { Circle ci=new Circle(5); ci.setRadius(5); ci.setCenter(0, 0); System.out.println(ci.getArea()); System.out.println(ci.getCircumference()); System.out.println(ci.getCenterx()); System.out.println(ci.getCentery()); }

}答案:78.5

31.400000000000002 0.0 0.0

2.定义图形类Shape,该类中有获得面积的方法getArea();定义长方形类Rect,该类是Shape的子类,类中有矩形长和宽的变量double a,double b,设置长和宽的方法setWidth()、setHeight(),使用getArea()求矩形面积;利用getArea方法实现题1中圆面积的求解。

class Shape { double getArea(double r){ return 0; } }

public class Rect extends Shape {

double a,b,area; Rect(double width,double heigh){ a=width; b=height;; } void setWidth(double width) { a=width; } void setHeight(double height) { b=height; } double getWidth(){ return a; } double getHeight(){ return b; } double getArea(){ area=a*b; return area; } }

public class A { public static void main(String args[]) { Rect rect=new Rect(); double w=12.76,h=25.28; rect.setWidth(w); rect.setHeight(h); System.out.println(\矩形对象的宽:\高:\ System.out.println(\矩形的面积:\ } }

答案:

圆的的面积:78.5

矩形对象的宽:12.76 高:25.28 矩形的面积:322.57280000000003

3. 编写Java应用程序,定义Animal类,此类中有动物的属性:名称 name,腿的数量legs,统计动物的数量 count;方法:设置动物腿数量的方法 void setLegs(),获得腿数量的方法 getLegs(),设置动物名称的方法 setKind(),获得动物名称的方法 getKind(),获得动物数量的方法 getCount()。定义Fish类,是

Animal类的子类,统计鱼的数量 count,获得鱼数量的方法 getCount()。定义Tiger类,是Animal类的子类,统计老虎的数量 count,获得老虎数量的方法 getCount()。定义SouthEastTiger类,是Tiger类的子类,统计老虎的数量 count,获得老虎数量的方法 getCount()。 public class Animal { String name; int legs; static int count; Animal(){count++;} void setLegs(int legs){ this.legs=legs; } int getLegs(){ return legs; } void setKind(String name){ this.name=name; } String getKind(){ return name; } int getCount(){ return count; } }

public class Fish extends Animal{

static int countFish; Fish(){countFish++;}

int getCount(){ return countFish; } }

public class Tiger extends Animal{

static int countTiger; Tiger(){countTiger++;}

int getCount(){ return countTiger; } }

public class SouthEastTiger extends Tiger{}

public class A { public static void main(String args[]){ Fish f=new Fish(); System.out.println(f.getCount()); Tiger t=new Tiger(); System.out.println(t.getCount()); SouthEastTiger st=new SouthEastTiger(); System.out.println(st.getCount()); } }

实验四 异常处理

1.建立exception包,编写TestException.java程序,主方法中有以下代码,确定其中可能出现的异常,进行捕获处理。

for(inti=0;i<4;i++){ intk; switch(i){ case0:intzero=0;k=911/zero;break; case1:intb[]=null;k?=b[0];break; case2:int c[]=new int[2];k=c[9];break; case3:charch=\ } }

package Exception;

public class TestException { public static void main(String[] args){ for(int i=0;i<4;i++){ try{ int k; switch(i){ case 0: int zero=0;k=911/zero;break; case 1: int b[]=null;k=b[0];break; case 2: int c[]=new int[2];k=c[9];break; case 3: char ch=\ } } catch(ArithmeticException e){ System.out.println(e.getMessage()); } catch(java.lang.NullPointerException e){ System.out.println(e.getMessage()); }

catch(ArrayIndexOutOfBoundsException e){ System.out.println(e.getMessage()); } catch(java.lang.StringIndexOutOfBoundsException e){ System.out.println(e.getMessage()); } } } }

运行结果: / by zero null 9

String index out of range: 99

2.建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),表示存入银行100元,当用方法withdrawal(150),withdrawal(-15)时会抛出自定义异常。 提示: InsufficientFundsException,NagativeFundsException为自定义的类,分别产生余额不足异常和取款为负数异常,需继承Exception类。

通过输出结果了解java异常的产生,并将该Java程序放在exception包中。 package Exception;//注解先建立一个package,然后在包中建立各种类 public class InsufficientFundsException extends Exception{ String s1; InsufficientFundsException(String t){ s1=t; }

public String getMassage1(){ return s1; } }

package Exception;

public class NagativeFundsException extends Exception{ String s; NagativeFundsException(String t){ s=t; }

public String getMassage(){

return s; } }

package Exception;

public class Bank extends Exception{ static double ba=0; Bank(double r){ ba=ba+r; } void withDrawal(double dAmount) InsufficientFundsException,NagativeFundsException{ if(dAmount>ba) throw new InsufficientFundsException(\取款余额不足\ else if(dAmount<0) throw new NagativeFundsException(\取款为负数\ else System.out.print(\银行里还剩余:\ } }

package Exception; import java.util.*; public class A{

public static void main(String args[] ){ Bank b=new Bank(100); Scanner sc=new Scanner(System.in); try { System.out.println(\请输入一个数\ b.withDrawal(sc.nextInt()); } catch(InsufficientFundsException e){ System.out.println(e.getMassage1()); } catch(NagativeFundsException e){ System.out.println(e.getMassage()); } } }

运行结果: 请输入一个数 80

银行里还剩余:20.0

实验五 输入输出

throws

1.编写TextRw.java的Java应用程序,程序完成的功能是:首先向TextRw.txt中写入自己的学号和姓名,读取TextRw.txt中信息并将其显示在屏幕上。 import java.io.*;

public class TextRw {

public static void main(String[] args) throws IOException { File f=new File(\ FileWriter fw=new FileWriter(f); fw.write(\学号 姓名\ fw.close(); FileReader fr=new FileReader(f); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } }

2.编写IoDemo.java的Java应用程序,程序完成的功能是:首先读取IoDemo.java源程序文件,再通过键盘输入文件的名称为iodemo.txt,把IoDemo.java的源程序存入 import java.io.*;

public class TextRw {

public static void main(String[] args) throws IOException{ String f=\

FileReader r=new FileReader(f); int i;

while((i=r.read())!=-1){ System.out.print((char)i); }

r.close();

BufferedReader w=new BufferedReader(new InputStreamReader(System.in)); System.out.print(\请目录和输入文本名\ String f1=w.readLine();

FileWriter w1=new FileWriter(f1); FileReader r1=new FileReader(f); int j;

while((j=r1.read())!=-1){ w1.write((char)j); }

w1.close();

} }

运行结果:public class Hello{

public static void main(String[] args){ System.out.println(\}

}请目录和输入文本名e:\\\\Hello.text 且会在e目录下产生Hello.text

3.编写BinIoDemo.java的Java应用程序,程序完成的功能是:完成1.doc文件的复制,复制以后的文件的名称为自己的学号姓名.doc。 import java.io.*;

public class BinIoDemo{

public static void main(String[] args) throws IOException{ File f1=new File(\

FileInputStream in=new FileInputStream(f1);

File f2 = new File(\“学号”+“姓名”.doc\ FileOutputStream out=new FileOutputStream(f2); byte[] buf = new byte[2048]; int num = in.read(buf); while (num != (-1)) { out.write(buf, 0, num); out.flush();

num = in.read(buf); }

in.close(); out.close(); } }

实验六 多线程编程

1.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。

通过Thread

public class Hw1Thread extends Thread{ String a; private int sleepTime; public Hw1Thread(String a){

super(a); this.a=a; sleepTime=(int)(Math.random()*6000); } public void run(){ int count1=0,count2=0; if(Thread.currentThread().getName().equalsIgnoreCase(\ for(int i=0;i<10;i++){ System.out.println(a); try{ Thread.sleep(sleepTime); count1++; if(count1>count2 && count1==10){ //判断哪个城市的输出次数先达到10,达到则终止输出 System.out.println(\ } else if(count2>count1 && count2==10){ System.out.println(\//判断哪个城市的输出次数先达到10,达到则终止输出 } } catch(InterruptedException exception){};//使用sleep方法需要抛出中断异常 } } if(Thread.currentThread().getName().equalsIgnoreCase(\ for(int i=0;i<10;i++){ System.out.println(a); try{ Thread.sleep(sleepTime); count2++; if(count1>count2 && count1==10){ System.out.println(\ } else if(count2>count1 && count2==10){ System.out.println(\ } } catch(InterruptedException exception){};//使用sleep方法需要抛出中断异常 (也可以在方法头抛出(throw)异常) } } } }

public class Hw1ThreadText { public static void main(String[] args) throws InterruptedException { Hw1Thread td1=new Hw1Thread(\ Hw1Thread td2=new Hw1Thread(\ td1.start(); td2.start(); } }

通过Runnable接口:

public class Hw1Thread implements Runnable{ String a; private int sleepTime; int count1=0,count2=0; public Hw1Thread(String a){ this.a=a; sleepTime=(int)(Math.random()*1000); } public void run(){ //重写run方法 if(Thread.currentThread().getName().equalsIgnoreCase(\ for(int i=0;i<10;i++){ System.out.println(\ try{ Thread.sleep(sleepTime); count1++; } catch(InterruptedException exception){}; //使用sleep方法需要抛出中断异常 if(count1>count2 && count1==10){ System.out.println(\ } else if(count2>count1 && count2==10){ System.out.println(\ } } } if(Thread.currentThread().getName().equalsIgnoreCase(\ for(int i=0;i<10;i++){ System.out.println(\ try{ Thread.sleep(sleepTime); count2++; if(count1>count2 && count1==10){ //判断哪个城市的输出次数先达到10,达到则终止输出

System.out.println(\ } else if(count2>count1 && count2==10){ System.out.println(\//判断哪个城市的输出次数先达到10,达到则终止输出 } catch(InterruptedException exception){};//使用sleep方法需要抛出中断异常 } } } }

public class Hw1ThreadText { public static void main(String[] args) throws InterruptedException { Hw1Thread td1=new Hw1Thread(\ Hw1Thread td2=new Hw1Thread(\ new Thread(td1,\ new Thread(td2,\ } }

2.用继承Thread类方法实现多线程程序。有两个学生小明和小红,小明准备睡10分钟以后开始听课,小红准备睡1小时以后开始听课,雷老师大喊三声“上课了”,小明醒后把小红吵醒,他们开始听课。 学生:小明、小红

睡觉:明:10min 红:60min 老师:喊三声 明醒->红醒。 上课。

class Stu extends Thread{

Thread student1,student2,teacher; Stu() {

teacher=new Thread(this); student1=new Thread(this); student2=new Thread(this); teacher.setName(\雷老师\ student1.setName(\小明\ student2.setName(\小红\ }

public void run() {

if(Thread.currentThread()==student1) {

try{ System.out.println(student1.getName()+\正在睡觉\

Thread.sleep(1000*60*10); }

catch(InterruptedException e) {

System.out.println(student1.getName()+\被老师叫醒了\ }

System.out.println(student1.getName()+\开始听课\ }

if(Thread.currentThread()==student2) {

try{ System.out.println(student2.getName()+\正在睡觉\ Thread.sleep(1000*60*60); }

catch(InterruptedException e) {

System.out.println(student2.getName()+\被小明叫醒了\ }

System.out.println(student2.getName()+\开始听课\ }

else if(Thread.currentThread()==teacher) { for(int i=1;i<=3;i++) {

System.out.println(\上课!\ try { Thread.sleep(500); }

catch(InterruptedException e){} }

student1.interrupt(); //吵醒student student2.interrupt(); } } }

public class A{

public static void main(String args[]) { Stu s=new Stu(); s.student1.start(); s.student2.start(); s.teacher.start(); } }

实验七 图像用户界面

1.编程实现如下界面:当在第一个文本框中输入直接回车,会在第二个文本框中得第一个文本框输入值的平方,单击求和,会在第二个文本框中得到两个文本框中的和。

import java.awt.*;

import java.awt.event.*;

public class Test implements ActionListener{ TextField tf,tf1; Button b; Frame f; Test() { f=new Frame(); f.setSize(150, 150); f.setLocation(300, 300); Panel p=new Panel(); Panel p1=new Panel(); Panel p2=new Panel(); tf=new TextField(10); tf1=new TextField(10); b=new Button(\求和\ p.add(tf);p1.add(tf1);p2.add(b); f.add(p,BorderLayout.NORTH); f.add(p1,BorderLayout.CENTER); f.add(p2,BorderLayout.SOUTH); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); tf.addActionListener(this); b.addActionListener(this); } public static void main(String[] args) { new Test(); } public void actionPerformed(ActionEvent e)

}

{ }

int i;

if(e.getSource()==tf){ i=Integer.parseInt(tf.getText()); tf1.setText(String.valueOf(i*i)); }else if(e.getSource()==b) { i=Integer.parseInt(tf.getText())+Integer.parseInt(tf1.getText()); tf1.setText(String.valueOf(i)); }

2.按照如下图所示的窗体布局,其中包含Label,TextField,Button控件,Label控件的名称为l1,l2,l3,l4,l5;TextField的大小为10,Button控件的名称如图所示。所完成的功能是:单击关闭按钮能够关闭窗体;单击“计算”按钮,将得出1号商品和2号商品的费用并显示在合计文本框中;输入1号商品的价格,如果2号商品的价格和1号商品价格相同,在1号商品显示价格控件中回车,2号商品的价格显示和1号商品相同;输入1号商品的数量,如果2号商品的数量和1号商品数量相同,在1号商品显示数量控件中回车,2号商品的数量和1号商品数量相同。

import java.awt.*;

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Price { public Price(){ Frame f=new Frame(\商品计费\

Label l1=new Label(\号商品价格\数量\ Label l3=new Label(\号商品价格\数量\ Label l5=new Label(\合计\创建标签 Button b=new Button(\计算\创建按钮 final TextField tf1=new TextField(10);final TextField tf2=new TextField(10); final TextField tf3=new TextField(10);final TextField tf4=new TextField(10);//文本框 final TextField tf5=new TextField(10); Panel p1=new Panel();Panel p2=new Panel();Panel p3=new Panel(); p1.add(l1);p1.add(tf1);p1.add(l2);p1.add(tf2); p2.add(l3);p2.add(tf3);p2.add(l4);p2.add(tf4); p3.add(b);p3.add(l5);p3.add(tf5);//使用这种布局添加方法可以使用Layout默认布局进行布局 f.add(p1,BorderLayout.NORTH); f.add(p2,BorderLayout.CENTER); f.add(p3,BorderLayout.SOUTH); f.setSize(400, 150); f.setLocation(200, 200); f.setVisible(true); //以上备注同实验1 以下蓝色字体按照题1中的思路编程

tf1.addKeyListener(new KeyListener(){

public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER){ tf3.setText(tf1.getText()); } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }); //对文本框1(\号商品价格\)添加键盘监控器,接收到回车符完成相应功能 tf2.addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER){ tf4.setText(tf2.getText()); } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }); //对文本框2(\数量\添加键盘监控器,接收到回车符完成相应功能 f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);

}

} });//窗体的关闭监控器 b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int p1,p2,num1,num2; p1=Integer.parseInt(tf1.getText());p2=Integer.parseInt(tf3.getText()); num1=Integer.parseInt(tf2.getText());num2=Integer.parseInt(tf4.getText()); tf5.setText(Integer.toString(p1*num1+p2*num2)); } });//按钮监控器 }

public static void main(String[] args) { new Price(); }

实验八 JDBC编程

1. 用access建立数据库ssm,库中有student表,表中字段有:学号(number),姓名(name),性别(gender),年龄 (age),成绩(score),科目(course)。 (1)使用“insert into”向表中添加5个你熟悉的同学的学号、姓名、年龄、成绩和科目,并将添加以后的学生信息显示在控制台端。 (2)使用“select ”条件查询得到成绩是80分以上的同学信息。 (3)使用“update ”将表中学号等于自己学号的成绩修改为85分,并将修改以后的表中所有学生信息显示在控制台端。 (4) 使用“delete ”将表中成绩高于80分以上的学生信息删除,并将删除以后的表中所有学生信息显示在控制台端。 //以下代码中已经屏蔽的内容只可执行一次,多次执行会产生重复错误 import java.sql.*;

public class DataTest { public static void main(String[] args) throws SQLException { try { Class.forName(\

} catch (ClassNotFoundException e) { e.printStackTrace(); } Connection con=DriverManager.getConnection(\ Statement state=con.createStatement(); /* state.executeUpdate(\INTO student VALUES (1209030107,'ou wen','female',20,76,'C')\ state.executeUpdate(\into student values (1209030118,'cheng ranran','male',21,85,'C')\ state.executeUpdate(\into student values (1209030109,'tang binxue','female',19,77,'C')\ state.executeUpdate(\ state.executeUpdate(\into student values (1209030150,'zhao kaifa','male',19,76,'C')\向数据库中添加一条信息 */ //ResultSet rs1=state.executeQuery(\查找student表中的所有信息 //ResultSet rs2=state.executeQuery(\选择成绩大于80的学僧 state.executeUpdate(\TE student SET score=85 WHERE number='1209030150'\更新自己的分数 //ResultSet rs3=state.executeQuery(\ state.executeUpdate(\删除分数大于80的学生信息 ResultSet rs4=state.executeQuery(\ /*System.out.println(\第一次添加后数据库中数据:\一下是输出语句 while(rs1.next()) { System.out.println(rs1.getString(\\\ System.out.println(); } System.out.println(\第一次添加后,成绩大于80分的成绩:\ while(rs2.next()) { System.out.println(rs2.getInt(1)+\\\\ System.out.println(); } System.out.println(\第一次添加后,表中自己的成绩修改为85分:\ while(rs3.next()) {

System.out.println(rs3.getInt(1)+\\\\ System.out.println(); }*/ System.out.println(\删除成绩大于80分的同学后,数据库中数据:\ while(rs4.next()) { System.out.println(rs4.getInt(1)+\\\\ System.out.println(); } con.close(); } }

System.out.println(rs3.getInt(1)+\\\\ System.out.println(); }*/ System.out.println(\删除成绩大于80分的同学后,数据库中数据:\ while(rs4.next()) { System.out.println(rs4.getInt(1)+\\\\ System.out.println(); } con.close(); } }

本文来源:https://www.bwwdw.com/article/0njp.html

Top