Java程序中的main方法声明中的参数类型是一个字符串数组,运行时,存放接收的参数,和C语言不同,第一个参数存放在下标为0的位置,第二个参数存放在下标为1的位置,其它的一次类推。下面的程序说明了参数的应用。
public class TestMainParameter {
public static void main(String[] args) {
//下面的循环,逐个输出数组args的每个元素
for(String str:args ){
System.out.println(str);
}
}
}
public class Args {
public static void main(String[] args) {
for(int i=0;i<args.length;i++){
System.out.println("第"+i+"个参数是"+args[i]);
}
}
}
斐波那契数列
1.递归法
import java.util.*;
import java.io.*;
public class Fib {
static int fib(int n){
if(n==1) return 0;
if(n==2) return 1;
return fib(n-1)+fib(n-2);
}
public static void main(String args[]){
int n;
Scanner cin=new Scanner(System.in);
n=cin.nextInt();
System.out.println(fib(n));
}
}
2.迭代法
import java.util.*;
import java.io.*;
public class fib {
static int fib[]=new int[30];
public static void main(String args[]){
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
fib[1]=0; fib[2]=1;
for(int i=3;i<=n;i++)
fib[i]=fib[i-1]+fib[i-2];
for(int i=1;i<=n;i++)
System.out.println(fib[n]);
}
}
素数
public class primes {
public static void main(String[] args) {
int i,j;
for( i = 2;i<= 100;i++) {
for(j = 2;j <= (int)Math.sqrt(i);j++)
if(i % j == 0) break;
if(j>=(int)Math.sqrt(i)) System.out.println(i );
}
}
}
public class Prime {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j;
label: for(i=2;i<100;i++)
{
for(j=2; j<i/2;j++)
if(i%j==0) continue label;
System.out.print(" "+i);
}
}
}
闰年
1 Scanner sc=new Scanner(System.in)
import java.util.Scanner;
public class LeapYear {
public static void main(String[]args){
int year;
Scanner sc=new Scanner(System.in);
year=sc.nextInt();
if((year%4==0&& year%100!=0)|| year%400==0) System.out.println("闰年");
else System.out.println("no不是 闰年");
}
}
2.BufferedReader
import java.io.*;
public class Leap {
public static void main(String[]args) throws IOException{
int year;
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
year=Integer.parseInt(str);
if((year%4==0&& year%100!=0)|| year%400==0) System.out.println("闰年");
else System.out.println("no不是 闰年");
}
}
3.
import java.util.Scanner;
public class LeapYear {
public boolean isLeap(int year){
if((year%4==0&& year%100!=0)|| year%400==0) return true;
else return false;
}
public static void main(String[]args){
LeapYear l=new LeapYear();
int year;
Scanner sc=new Scanner(System.in);
year=sc.nextInt();
if(l.isLeap(year)) System.out.println(year);
}
}
1.“输入两个实数,计算它们的平均值并显示在屏幕上”,要求从控制台输入输出数据。
方法一
package Practice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Average {
public static void main(String[] args) throws IOException {
String s1,s2;
double x,y,z; BufferedReader对象只将回车看作输入结束,得到的字符串
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
x=Double.parseDouble(s1);
s2=in.readLine();
y=Double.parseDouble(s2);
z=(x+y)/2;
System.out.println(z);
//System.out.println((x+y)/2);
}
}
方法二
package Practice;
import java.util.Scanner;
public class Averages {
public static void main(String[] args) {
//Scanner对象把回车,空格,tab键都看作输入结束,直接 用sc.next()得到的是字符串形式
Scanner sc=new Scanner(System.in);
double a=sc.nextDouble();
double b=sc.nextDouble();
double c=(a+b)/2;
System.out.println(c);
}
}
2. 求解一元一次方程
3. 统计输入一个字符串,其中字母、空格、数字、其它字符的个数
package Practice;
import java.util.Scanner;
public class Char {
public static void main(String[] args) {
char ch;
int a1=0,a2=0,a3=0,a4=0;
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch>='a'&&ch<='z' ||ch>='A' && ch<='Z') a1++;
else if(ch>='0'&&ch<='9') a2++;
else if(ch==' ') a3++;
else a4++;
}
System.out.println(a1+" "+a2+" "+a3+" "+a4);
}
}
- 解释下面的程序运行结果输出为什么是null
public class My {
String s;
public void My(){
s = "Constructor";
}
public void go() {
System.out.println(s);
}
public static void main(String args[]) {
My m = new My();
m.go();
}
}
2. public class Demo{
public static void main(String[ ] args){
int i;
System.out.println(i);
}
}
Jiao教师类
Teacher.java
public class Teacher {
String name,sex;
int age;
String course;
int result;
public Teacher(String name, String sex, int age, String course, int result) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.course = course;
this.result = result;
}
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
public int getAge() { return age;}
public void setAge(int age) { this.age = age; }
public String getCourse() { return course; }
public void setCourse(String course) { this.course = course; }
public void setResult(String result){ // 执果索因
if(result.equals("优秀")) this.result= 1;
else if(result.equals("良好")) this.result= 2;
else if(result.equals("一般")) this.result= 3;
else if(result.equals("差")) this.result= 4;
}
public String getResult() {
if(result==1) return "优秀";
else if(result==2) return "良好";
else if(result==3) return "一般";
else return "差";
}
public void getDetails(){
System.out.printf("%8s %9s %8s %9s %11s" ,"姓名:" , "性别:" ," 年龄:" , " 讲授课程:" , " 教学效果:");
System.out.println();
System.out.printf("%8s %9s %8s %9s %11s",this.getName(),this.getSex(),this.getAge(),this.getCourse(),this.getResult());
}
}
Test.java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Teacher t=new Teacher("Tom","M",35,"Java",1);
t.getDetails();
}
}
课程类
1.Course.java
public class Course {
int cNumber,cUnit;
String cName;
public Course(int cNumber, String cName,int cUnit) {
super();
this.cNumber = cNumber;
this.cName = cName;
this.cUnit = cUnit;
}
public int getcNumber() { return cNumber;}
public void setcNumber(int cNumber) { this.cNumber = cNumber; }
public int getcUnit() { return cUnit; }
public void setcUnit(int cUnit) { this.cUnit = cUnit; }
public String getcName() { return cName; }
public void setcName(String cName) { this.cName = cName; }
public void printCourseInfo() {
// TODO Auto-generated method stub
System.out.println(cNumber+" "+cName+" "+cUnit);
}
}
2.Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a,b;
String c;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
c=sc.nextLine();
b=sc.nextInt();
Course course=new Course(a,c,b);
course.printCourseInfo();
}
}
鸽类 鹰类
- 哈希值
System.out.println(g.hashCode()); // 哈希值
System.out.println(Integer.toHexString(g.hashCode())); // 十六制形式
Class c = g.getClass();
System.out.println(c.getName());
System.out.println(c.getName()+"@@@@@@"+Integer.toHexString(g.hashCode()));
- 按照要求完成程序:
- 第一个类是图形类(Shape),含有一个成员变量color(字符串类型),一个没有参数的构造方法,以及一个有一个字符串类型参数的构造方法来初始化颜色变量,还有一个返回颜色变量值的成员方法show,以及一个抽象方法getArea获取面积,返回值为double类型;
2.第二个类是圆形类(Circle)继承自图形类,含有一个成员变量半径r,有一个有两个参数的构造方法,来初始化颜色和半径,一个方法getArea,返回值为double,获取圆的面积值。
3.第三个类是矩形类(Rectangle)继承自图形,含有两个double类型的成员变量长a和宽b,有一个有三个参数的构造方法,来初始化颜色、长和宽,一个方法getArea,返回值为double,获取矩形的面积值。
4.第四个类是测试类(TestShape),分别定义圆形类和矩形类的实例对象,并用show方法,getArea方法来测试自己的定义
多线程同步
假设某银行账户可接受顾客的汇款,每做一次汇款,便可计算出账户的总金额。现有两个顾客,每人都分3次,每次100元将钱汇入。试编写一个程序,模拟实际作业。
4、程序清单
class CCount{
private int sum;
public CCount(int sum){this.sum=sum;}
public synchronized void add(String str,int n){
sum+=n;
System.out.println(str+": "+"sum= "+sum);
}
public int getSum(){
return sum;
}
}
class CCustomer extends Thread { // CCustomer类,继承自Thread类
CCount count;
public CCustomer(CCount count){this.count=count;}
public void run(){
for(int i=1;i<=3;i++) {
count.add(this.getName(),100); // 将100元分三次汇入
try{
sleep((int)(1000)); // 小睡几秒钟
}catch(InterruptedException e){}
}
}
}
public class Sy7{
public static void main(String args[]) {
CCount count=new CCount(1000);
CCustomer c1=new CCustomer(count);
CCustomer c2=new CCustomer(count);
c1.start();
c2.start();
}
}
AWT事件处理
(1)、使用JFrame类显示一个简单的窗口,并在窗口上端添加一个面板,在窗口下端添加一个按钮。按钮具有的功能:在单击按钮时改变面板的背景色。同时使得窗口能够通过单击关闭按钮进行关闭。
(2)、在窗口中创建复选框、单选框、文本区域、单行文本框等组件,并实现根据用户输入的10 进制数,选择不同选项可转换为2、8、16 进制数。
(3)、在窗口中添加菜单栏,在菜单栏添加菜单项,并添加下拉菜单和2 级菜单,通过选择菜单项可以执行不同操作。
4、程序清单
//(1)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Sy8 extends JFrame implements ActionListener{
JPanel pan;
JButton bt;
public Sy8(){
pan=new JPanel();
bt=new JButton("变色");
bt.addActionListener(this);
Container con=getContentPane(); con.setLayout(new BorderLayout());
con.add(pan,BorderLayout.CENTER); con.add(bt,BorderLayout.SOUTH);
setSize(300,400); setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float a,b,c;
if(e.getSource()==bt){
a=(float)(Math.random()); b=(float)(Math.random());
c=(float)(Math.random());
pan.setBackground(new Color(a,b,c));
}
}
public static void main(String args[]){ Sy5 frm=new Sy8(); }
}
实验8: JDBC编程
了解JDBC核心API,利用JDBC核心API,建立数据库连接、执行SQL语句、取得查询集、数据类型支持等功能。
二、实验主要设备及使用要求
按操作计算机的要求使用好计算机设备。
三、实验原理或算法
在Java中使用数据库进行JDBC编程时,Java程序中通常应包含下述几部分内容:
(1) 在程序的首部用import语句将java.sql包引入程序:
import java.sql.*;
(2) 使用Class.forName( )方法加载相应数据库的JDBC驱动程序。若以加载jdbc-odbc桥为例,则相应的语句格式为:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
(3) 定义JDBC的URL对象。例如:
String conURL="jdbc:odbc:TestDB";
其中TestDB是我们设置的要创建的数据源。
(4) 连接数据库。
Connection s=DriverManager.getConnection(conURL);
(5) 使用SQL语句对数据库进行操作。
(6) 使用close( )方法解除Java与数据库的连接并关闭数据库: s.close( );
(一)配置ODBC数据源
1. 从开始菜单中,选择设置|控制面板。
2. 在控制面板中选择"32位 ODBC"。
3. 打开"32位 ODBC"后,看到的应该是一个卡片式对话框,上面一排有多个卡片标签,其中包括"用户DSN"、"系统DSN"、"文件DSN"等等。选择"系统DSN"。
4. 单击"系统DSN"中的"添加…"按钮,弹出一个对话框。
5. 在对话框中,列出了当前系统支持的ODBC数据源的驱动程序,选择"Microsoft Access Driver",单击"完成"按钮,弹出一个对话框。
6. 在对话框中,向"数据源"文本框内输入数据源的名字,这个名字可以任取,在这个例子中,我们输入的名字是"vfox"。然后,单击"创建"按钮。
7. 在对话框中,选择数据库存放的目录,然后向"数据库名"文本框内输入数据库的名字,这个名字可以任取,在这个例子中,我们输入的名字是"vfox"。然后,单击"确定"按钮,会弹出显示"数据库创建成功"的对话框。
8. 依次单击"确定"按钮。
(二)在MySQL中创建数据库webdb,并创建表news ,表结构如下:
字段名 | 类型 | 长度 | 备注 |
newsid | int | 11 | 主键,自增 |
title | varchar | 200 | 标题 |
author | varchar | 32 | 作者 |
hit | int | 11 | 点击量 |
(三)编写程序,实现对news表的增删改查操作。
插入数据代码:
package zsl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertNews {
public static void main(String[] args)throws ClassNotFoundException,SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection
("jdbc:mysql://127.0.0.1:3306/webdb?user=root&password=1");
Statement stmt=cn.createStatement();
int flag=stmt.executeUpdate("insert into news(title,author,hit)values('我院荣获全国独立学院','管理员','888')");
if (flag>0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
stmt.close();
cn.close();
}
}
查询数据代码:
package zsl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectNews {
public static void main(String[] args)throws ClassNotFoundException,SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection
("jdbc:mysql://127.0.0.1:3306/webdb?user=root&password=1");
Statement stmt=cn.createStatement();
ResultSet rs=stmt.executeQuery("select*from news");
while (rs.next()){
System.out.println("newsid-->+rs.getInt(1)");
System.out.println("title-->+rs.getInt(2)");
System.out.println("author-->+rs.getInt(3)");
System.out.println("hit-->+rs.getInt(4)");
}
rs.close();
stmt.close();
cn.close();
}
}
删除数据代码:
package zsl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DeletNews {
public static void main(String[] args)throws SQLException, ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection
("jdbc:mysql://127.0.0.1:3306/webdb?user=root&password=1");
Statement stmt=cn.createStatement();
int flag=stmt.executeUpdate(" delete from news where author='管理员'");
if (flag>0){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
stmt.close();
cn.close();
}
}
修改数据代码:
package zsl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class UpdateNews {
public static void main(String[] args)throws ClassNotFoundException,SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection
("jdbc:mysql://127.0.0.1:3306/webdb?user=root&password=1");
Statement stmt=cn.createStatement();
int flag=stmt.executeUpdate("update news set title='我院荣获湖南发展最快学院',hit=666 where author='管理员'");
if (flag>0){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
stmt.close();
cn.close();
}
}
实验二 Java基本语法练习
1、实验目的
理解Java程序语法结构,掌握顺序结构,选择结构和循环结构语法的程序设计方法;通过以上内容,掌握Java语言的编程规则。
2、方法原理
Java程序语法结构与编程规则。
3、实验内容
• 习题3 : 2、9 6、7、8、10
4、程序清单
// 习题3_2 : Prime.java
public class Prime {
public static void main(String[] args) {
boolean isPrime;
for (int x = 2; x <= 100; x++) {
isPrime=true;
for (int i=2; i<x; i++) {
if (x % i == 0) { isPrime=false; break; }
}
if(isPrime) System.out.print(x+"\t");
}
}
}
// 习题3_9 : Ex3_9.java
import java.util.Scanner;
class Ex3_9{
public static void main(String args[]) {
int score,count=0,countA=0,countB=0,countC=0;
Scanner in=new Scanner(System.in);
while (true){
score=in.nextInt();
if (score<0 || score >100) continue;
count++;
switch (score<60?'C':score<=75?'B':'A') {
case 'C': countC++; break;
case 'B': countB++; break;
case 'A': countA++; break;
}
if (count==5) break;
}
System.out.println(countA+" "+countB+" "+countC);
}
}
实验三 类与对象的基本操作
1、实验目的
通过编程和上机实验理解Java语言是如何体现面向对象编程基本思想,了解类的封装方法,以及如何创建类和对象,了解成员变量和成员方法的特性,掌握OOP方式进行程序设计的方法。
2、方法原理
类与对象的创建方法
3、实验内容
(1) 将笛卡儿坐标系上的点定义为一个服务类Point,Point类求坐标系上两点间的距离。设计测试Point服务类的应用程序主类,显示输出已创建对象间的距离。
(2) 习题4: 5、6、 7 、8
4、程序清单
//Sy3.java
class Point {
int x,y;
public Point(int x,int y){
this.x=x; this.y=y;
}
public double distance (Point p){
return Math.sqrt(( (x-p.x)*(x-p.x)+Math.pow(y-p.y,2) ) );
}
}
public class Sy3{
public static void main(String args[]) {
double d;
Point p1=new Point(1,1);
Point p2=new Point(2,3);
d=p1.distance(p2);
System.out.println(d);
}
}
//习题4_7 : CTrapezoid.java
class CTrapezoid {
int upper,base,height;
public CTrapezoid(int u,int b, int h){
upper=u; base=b; height=h;
}
public double area(){
return (upper+base)*height/2.0;
}
void show(){
System.out.println("upper="+upper+" base="+base+" height="+height);
}
public static void main(String args[]) {
CTrapezoid obj=new CTrapezoid(4,9,5);
obj.show();
System.out.println("area="+obj.area());
}
}
实验四 数组与字符串
1、实验目的
掌握Java中的数组概念、声明、创建、初始化与使用; 熟练掌握Java的数组编程方法;掌握Java中字符串的概念;熟练掌握Java中String类、StringBuffer类中的有关方法应用。
2、方法原理
Java数组的声明与使用规则、字符串操作方法的调用格式。
3、实验内容
(1) 找出一个二维数组的鞍点,即该位置上的元素在该行上最大,该列上最小。
(2) 习题5 : 3、 4、5 、8
4、程序清单
public class Sy4{
public static void main(String[] args){
final int Size=3;
int[][] array=new int[Size][Size];
int i=0,j=0;
for ( i=0;i<Size;i++){
for ( j=0;j<Size;j++){
array[i][j]=(int)(Math.random()*100);
System.out.print(array[i][j]+" ");
}
System.out.println();
}
label:
for( i=0;i<Size;i++){
int rowMax=array[i][0];
int col=0;
for( j=1;j<Size;j++){
if(array[i][j]> rowMax){
rowMax=array[i][j];
col=j;
}
}
for(int k=0;k<Size;k++)
if(array[k][col]<rowMax)
continue label;
System.out.println("("+i+" "+j+"):"+rowMax);
}
}
}
实验五 类的继承与多态
1、实验目的
通过编程和上机实验,了解类的继承性和多态性的作用。
2、方法原理
继承与多态的实现。
3、实验内容
(1)编写求解一元多次方程的程序,要求:(1)包含一元一次方程、一元二次方程
(2) 按照要求完成程序
第一个类是图形类(Shape),含有一个成员变量color(字符串类型),一个没有参数的构造方法,以及一个有一个字符串类型参数的构造方法来初始化颜色变量,还有一个返回颜色变量值的成员方法show,以及一个抽象方法getArea获取面积,返回值为double类型;
第二个类是圆形类(Circle)继承自图形类,含有一个成员变量半径r,有一个有两个参数的构造方法,来初始化颜色和半径,一个方法getArea,返回值为double,获取圆的面积值。
第三个类是矩形类(Rectangle)继承自图形,含有两个double类型的成员变量长a和宽b,有一个有三个参数的构造方法,来初始化颜色、长和宽,一个方法getArea,返回值为double,获取矩形的面积值。
第四个类是测试类(TestShape),分别定义圆形类和矩形类的实例对象,并用show方法,getArea方法来测试自己的定义
(3) 习题4 : 4
(4) 习题5: 7、8
4、程序清单
// (1)
interface Idcfc { double getx1(); }
class Ycfc implements Idcfc {
public double a, b;
public Ycfc(double a, double b) { this.a = a; this.b = b; }
public double getx1() { return -b/a; }
}
class Ecfc extends Ycfc {
double c;
public Ecfc(double a1, double b1, double c1) { super(a1, b1); this.c = c1; }
public double getx1() {
double dt = Math.pow(b, 2.0) - 4 * a * c;
return ((-b + Math.sqrt(dt)) / (2 * a));
}
public double getx2() {
double dt = Math.pow(b, 2.0) - 4 * a * c;
return ((-b - Math.sqrt(dt)) / (2 * a));
}
}
public class Sy5 {
public static void main(String args[]) {
Ycfc ycfc = new Ycfc(4.0, 10.0);
System.out.println("ycfc:x1 = " + ycfc.getx1());
Ecfc ecfc = new Ecfc(1.0, 6.0, 5.0);
System.out.println("ecfc:x1 = " + ecfc.getx1());
System.out.println("ecfc:x2 = " + ecfc.getx2());
}
}
// (2)
abstract class CShape{
protected String color;
public CShape(String color){ this.color=color; }
public String show(){ return color; }
public abstract double getArea();
}
class CCircle extends CShape{
protected double r;
public CCircle(double r,String color){ super(color); this.r=r; }
public double getArea( ){ return Math.PI*r*r; }
}
class CRectangle extends CShape{
protected double a,b;
public CRectangle (double a,double b,String color){
super(color); this.a=a; this.b=b;
}
public double getArea( ){ return a*b; }
}
public class TestShape{
public static void main(String args[]) {
CCircle c=new CCircle(10,"yellow");
System.out.println(c.getArea());
System.out.println(c.show());
CRectangle rec=new CRectangle (20,10,"yellow");
System.out.println(rec.getArea());
System.out.println(rec.show());
}
}
实验六 文件输入输出流
1、实验目的
熟悉流式输入输出方法;掌握文件的存取操作。
2、方法原理
java.io包中定义了多种I/O流类型实现数据I/O功能。输入流只能从中读取数据,而不能向其写数据;输出流则只能向其写出数据,而不能从中读取数据。
3、实验内容
(1)将保存在本地机当前文件夹中的SY6_1.HTML 文本文件的内容在屏幕上显示出来,然后将其另存为SY6_1.txt 文件。
(2) 习题8: 4、5
4、程序清单
//(1) SY6_1.java 程序文件,源代码如下
import java.io.*;
public class SY6_1 {
public static void main(String[] args) throws IOException {
FileReader in=new FileReader("SY6_1.HTML");//建立文件输入流
BufferedReader bin=new BufferedReader(in);//建立缓冲输入流
FileWriter out=new FileWriter("SY6_1.txt",true);//建立文件输出流
String str;
while ((str=bin.readLine())!=null) {
//将缓冲区内容通过循环方式逐行赋值给字符串str
System.out.println(str);//在屏幕上显示字符串str
out.write(str+"\n");//将字符串str 通过输出流写入SY6_1.txt 中
}
in.close();
out.close();
}
}
实验七 多线程同步
1、实验目的
掌握线程设计方法;了解线程调度机制;理解线程同步机制。
2、方法原理
通过继承Thread或通过Runnable接口创建线程,Java语言实现互斥的方法:提供保留字synchronized.
3、实验内容
假设某银行账户可接受顾客的汇款,每做一次汇款,便可计算出账户的总金额。现有两个顾客,每人都分3次,每次100元将钱汇入。试编写一个程序,模拟实际作业。
4、程序清单
class CCount{
private int sum;
public CCount(int sum){this.sum=sum;}
public synchronized void add(String str,int n){
sum+=n;
System.out.println(str+": "+"sum= "+sum);
}
public int getSum(){
return sum;
}
}
class CCustomer extends Thread { // CCustomer类,继承自Thread类
CCount count;
public CCustomer(CCount count){this.count=count;}
public void run(){
for(int i=1;i<=3;i++) {
count.add(this.getName(),100); // 将100元分三次汇入
try{
sleep((int)(1000)); // 小睡几秒钟
}catch(InterruptedException e){}
}
}
}
public class Sy7{
public static void main(String args[]) {
CCount count=new CCount(1000);
CCustomer c1=new CCustomer(count);
CCustomer c2=new CCustomer(count);
c1.start();
c2.start();
}
}
实验八 AWT事件处理
1、实验目的
理解Java的事件处理机制,掌握为不同组件编写不同事件处理程序的方法。
2、方法原理
Java的事件处理机制。
3、实验内容
(1)、使用JFrame类显示一个简单的窗口,并在窗口上端添加一个面板,在窗口下端添加一个按钮。按钮具有的功能:在单击按钮时改变面板的背景色。同时使得窗口能够通过单击关闭按钮进行关闭。
(2)、在窗口中创建复选框、单选框、文本区域、单行文本框等组件,并实现根据用户输入的10 进制数,选择不同选项可转换为2、8、16 进制数。
(3)、在窗口中添加菜单栏,在菜单栏添加菜单项,并添加下拉菜单和2 级菜单,通过选择菜单项可以执行不同操作。
4、程序清单
//(1)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Sy8 extends JFrame implements ActionListener{
JPanel pan;
JButton bt;
public Sy8(){
pan=new JPanel();
bt=new JButton("变色");
bt.addActionListener(this);
Container con=getContentPane(); con.setLayout(new BorderLayout());
con.add(pan,BorderLayout.CENTER); con.add(bt,BorderLayout.SOUTH);
setSize(300,400); setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float a,b,c;
if(e.getSource()==bt){
a=(float)(Math.random()); b=(float)(Math.random());
c=(float)(Math.random());
pan.setBackground(new Color(a,b,c));
}
}
public static void main(String args[]){ Sy5 frm=new Sy8(); }
}