当前位置:文档之家› java大学实用教程课后答案

java大学实用教程课后答案

习题解答
第一章 作业题
1.
public class Hello{
public static void main (String args[ ]){
System.out.pintln(“早上好,good Morning”);
}
}

2.
import java.applet.*;
import java.awt.*;
public class Boy extends Applet {
public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawString("你好,hello",12,30);
}
}

第二章 作业题
1.
public class ZuoYe2_1{
public static void main (String args[ ]){
char c='а';
System.out.println("字母"+c+"在unicode表中的顺序位置:"+(int)c);
System.out.println("字母表:");
while(c<='я'){
System.out.print(" "+c);
c=(char)(c+1);
}
}
}
2.
import java.util.*;
public class ZuoYe2_2{
public static void main (String args[ ]){
Scanner reader=new Scanner(System.in);
long chengji=1;
int m=0;
while(reader.hasNextInt()){
int x=reader.nextInt();
m=m+1;
chengji=chengji*x;
}
System.out.println(m+"个数的乘积为"+chengji);
}
}
第三章 作业题
1.
import java.util.*;
public class ZuoYe3_1{
public static void main (String args[ ]){
Scanner reader=new Scanner(System.in);
double y=0,x=0;
x=reader.nextDouble();
if(x<0)
y=-1+2*x;
else if(x==0)
y=-1;
else if(x>0)
y=-1+3*x;
System.out.println(y);
}
}
2.
public class ZuoYe3_2{
public static void main(String args[]){
int sum=0,m=3,n=7,a=1;
while(a<=1000){
if(a%m==0&&a%n==0)
sum=sum+a;
a++;
}
System.out.println("sum="+sum);
}
}
3.
public class ZuoYe3_3
{
public static void main(String args[])
{
long sum=0,a=8,item=a,n=10,i=1;
for(i=1;i<=n;i++)
{ sum=sum+item;
item=item*10+a;
}
System.out.println(sum);
}
}
4.
public class ZuoYe3_4
{
public static void main(String args[])
{
double sum=0,a=1,b=1,fuhao=1,item=a/b;
int i=1;
while(i<=1000)
{
sum=sum+fuhao*item;
i++;
fuhao=fuhao*(-1);
b=b+2;
item=a/b;
}
System.out.println("sum="+sum);
}
}

5.
public class ZuoYe3_5
{
public static void main(String args[])
{
double sum=0,a=1;
int i=1;
while(i<=20)
{
if(i>=10)
sum=sum+a;
i++;
a=a*i;
}
System.out.println("sum="+sum);
}
}
8.
第四章 作业题
1.
class DengCha{
int start,d;
DengCha(){
}
DengCha(int start,int d){
this.start=start;
this.d=d;
}
void setStart(int s){
start=s;
}
void setD(int d){
this.d=d;
}
int getSum(int n){
int

sum=0,i=1;
while(i<=n){
sum=sum+start;
start=start+d;
i++;
}
return sum;
}
}
public class ZuoYe4_1
{
public static void main (String args[ ])
{
DengCha shulie=new DengCha(2,3);
System.out.println(shulie.getSum(100));
shulie.setStart(10);
shulie.setD(5);
System.out.println(shulie.getSum(9));
}
}

2.
class Letter{
public void printLetter(){
for(char c='a';c<='z';c++)
System.out.print(" "+c);
}
}
public class ZuoYe4_2
{
public static void main (String args[ ])
{
Letter p=new Letter();
p.printLetter();
}
}
3.
class SquareEquation{
double a,b;
static double c;
double root1,root2;
boolean boo;
public SquareEquation(double a,double b,double c){
this.a=a;
this.b=b;
SquareEquation.c=c;
if(a!=0){
boo=true;
}
else{
boo=false;
}
}
public void getRoots(){
if(boo){
System.out.println("是一元2次方程");
double disk=b*b-4*a*c;
if(disk>=0){
root1=(-b+Math.sqrt(disk))/(2*a);
root2=(-b-Math.sqrt(disk))/(2*a);
System.out.printf("方程的根:%f,%f\n",root1,root2);
}
else{
System.out.printf("方程没有实根\n");
}
}
else{
System.out.println("不是一元2次方程");
}
}
public void setCoefficient(double a,double b,double c){
this.a=a;
this.b=b;
SquareEquation.c=c;
if(a!=0){
boo=true;
}
else{
boo=false;
}
}
}
public class ZuoYe4_3{
public static void main(String args[ ]){
SquareEquation equation1=new SquareEquation(4,5,1);
SquareEquation equation2=new SquareEquation(3,5,-7);
equation1.getRoots();
equation2.getRoots();
}
}
4.
import java.util.Scanner;
class A{
int f(int m,int n){
if(m*n<0)
{ System.out.println("有负数,程序退出");
System.exit(0);
}
if(m{ int temp=m;
m=n;
n=temp;
}
int a=m,b=n;
int r=m%n;
while(r!=0)
{ m=n;
n=r;
r=m%n;
}
return n;
}
}
class B{
A a;
B(){
a=new A();
}
int g(int m,int n){
int temp=a.f(m,n);
return m*n/temp;
}
}
public class ZuoYe4_4
{
public static void main (String args[ ])
{
Scanner reader=new Scanner(System.in);
System.out.println("输入2个正整数,程序计算出它们的最大公约数和最小公倍数");
System.out.print("输入第一个整数:");
int m=reader.nextInt();
System.out.print("输入第二个整数:");
int n=reader.nextInt();
A a=new A

();
B b=new B();
System.out.println(m+"和"+n+"的最大公约数是"+a.f(m,n));
System.out.println(m+"和"+n+"的最小公倍数是"+b.g(m,n));
}
}
5.

import java.applet.Applet;
import java.awt.*;
public class Example4_10 extends Applet
{
Button redbutton;
public void init()
{
redbutton=new Button("我是一个红色的按钮");
redbutton.setBackground(Color.red);
redbutton.setForeground(Color.white);
add(redbutton);
}
}

第五章 作业题
1.
import java.util.Scanner;
class A
{
public int f(int m,int n)
{
if(m{
int temp=m;
m=n;
n=temp;
}
int r=m%n;
while(r!=0)
{
m=n;
n=r;
r=m%n;
}
return n;
}
}
class B extends A
{
public int f(int m,int n)
{
int division=super.f(m,n);
return (m*n)/division;
}
}
public class ZuoYe5_1
{
public static void main (String args[ ])
{
A a=new A();
B b=new B();
Scanner reader=new Scanner(System.in);
System.out.println("输入2个整数,程序计算出它们的最大公约数和最小公倍数");
System.out.print("输入第一个整数:");
int m=reader.nextInt();
System.out.print("输入第二个整数:");
int n=reader.nextInt();
if(m*n<0)
{ System.out.println("有负数,程序退出");
System.exit(0);
}
System.out.printf("%d和%d的最大公约数是%d\n",m,n,a.f(m,n));
System.out.printf("%d和%d的最小公倍数是%d\n",m,n,b.f(m,n));
}
}

2.
abstract class A{
public abstract void f(int x);
public abstract void g(int x,int y);
public abstract double h(double x);
}
class A1 extends A{
public void f(int x){
System.out.println(x);
}
public void g(int x,int y){
int z=x+y;
System.out.println(z);
}
public double h(double x){
return x*x;
}
}
class A2 extends A{
public void f(int x){
System.out.println("Hello:"+x);
}
public void g(int x,int y){
int z=x-y;
System.out.println(z);
}
public double h(double x){
return Math.sqrt(x);
}
}
class A3 extends A{
public void f(int x){
System.out.println("你好:"+x);
}
public void g(int x,int y){
double z=(double)x/y;
System.out.println(z);
}
public double h(double x){
return 1/x;
}
}
public class ZuoYe5_2{
public static void main(String args[ ]){
A a=new A1();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
a=new A2();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
a=new A3();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
}
}
3.
interface A{
public abstract void f(int x)

;
public abstract void g(int x,int y);
public abstract double h(double x);
}
class A1 implements A{
public void f(int x){
System.out.println(x);
}
public void g(int x,int y){
int z=x+y;
System.out.println(z);
}
public double h(double x){
return x*x;
}
}
class A2 implements A{
public void f(int x){
System.out.println("Hello:"+x);
}
public void g(int x,int y){
int z=x-y;
System.out.println(z);
}
public double h(double x){
return Math.sqrt(x);
}
}
class A3 implements A{
public void f(int x){
System.out.println("你好:"+x);
}
public void g(int x,int y){
double z=(double)x/y;
System.out.println(z);
}
public double h(double x){
return 1/x;
}
}
public class ZuoYe5_3{
public static void main(String args[ ]){
A a=new A1();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
a=new A2();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
a=new A3();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
}
}
4.
class Cubic
{ double getCubic(int n)
{ return 0;
}
}
abstract class Sqrt
{ public abstract double getSqrt(int x);
}
class A
{ void f(Cubic cubic)
{ double result=cubic.getCubic(3);
System.out.println(result);
}
}
public class ZuoYe5_4
{ public static void main(String args[])
{ A a=new A();
a.f(new Cubic()
{ double getCubic(int n)
{ return n*n*n;
}
}
);
Sqrt ss=new Sqrt()
{ public double getSqrt(int x)
{ return Math.sqrt(x);
}
};
double m=ss.getSqrt(5);
System.out.println(m);
}
}

5.
class IntegerException extends Exception
{ String message;
IntegerException(int m)
{ message="年龄"+m+"不合理";
}
public String toString()
{ return message;
}
}
class People
{ private int age=1;
public void setAge(int age) throws IntegerException
{
if(age>=160||age<=0)
throw new IntegerException(age); //方法抛出异常,导致方法结束
else
this.age=age;
}
public int getAge()
{ System.out.println("年龄"+age+"合理");
return age;
}
}
public class ZuoYe6_5
{ public static void main(String args[])
{ People wang=new People(),
zhang=new People();
try { wang.setAge(189);
System.out.println(wang.getAge());
}
catch(IntegerException e)
{ System.out.println(e.toString());
}
try { zhang.setAge(28);

System.out.println(zhang.getAge());
}
catch(IntegerException e)
{ System.out.println(e.toString());
}
}
}
第六章 作业题
1.
import java.util.regex.*;
import java.util.*;
public class ZuoYe6_1{
public static void main(String args[ ]){
Scanner reader=new Scanner(System.in);
String s1=reader.nextLine();
Pattern p;
Matcher m;
p=https://www.doczj.com/doc/cd13479847.html,pile("[24680]A[13579]{2}");
m=p.matcher(s1);
while(m.find()){
String str=m.group();
System.out.print("从"+m.start()+"到"+m.end()+"匹配模式子序列:");
System.out.println(str);
}
}
}
2.
import java.util.regex.*;
import java.util.*;
public class ZuoYe4_1{
public static void main(String args[ ]){
Scanner reader=new Scanner(System.in);
String s1=reader.nextLine();
Pattern p;
Matcher m;
p=https://www.doczj.com/doc/cd13479847.html,pile("\\d+");
m=p.matcher(s1);
while(m.find()){
String str=m.group();
System.out.print(str);
}
}
}
第七章 作业题
1.

import java.util.*;
public class ZuoYe7_2
{ public static void main(String args[])
{
int year,month;
try
{
year=Integer.parseInt(args[0]);
month=Integer.parseInt(args[1])+1;

}
catch(NumberFormatException e)
{
year=2004;
month=1;
}
System.out.println(" 日 一 二 三 四 五 六");
Calendar 日历=Calendar.getInstance();
日历.set(year,month,1);
int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;
String a[]=new String[星期几+31];
for(int i=0;i<星期几;i++)
{ a[i]="**";
}
for(int i=星期几,n=1;i<星期几+31;i++)
{ if(n<=9)
a[i]=String.valueOf(n)+" ";
else
a[i]=String.valueOf(n) ;
n++;
}
for(int i=0;i{ if(i%7==0)
{ System.out.println("");
}
System.out.print(" "+a[i]);
}
}
}

2.
class ZuoYe7_2
{ public static void main(String args[])
{
int year1,month1,day1,year2,month2,day2;
try
{
year1=Integer.parseInt(args[0]);
month1=Integer.parseInt(args[1]);
day1=Integer.parseInt(args[2]);
year2=Integer.parseInt(args[3]);
month2=Integer.parseInt(args[4]);
day2=Integer.parseInt(args[5]);
}
catch(NumberFormatException e)
{

year1=2009;
month1=0;
day1=1;
year2=2008;
month2=0;
day2=1;
}
Calendar calendar=Calendar.getInstance();
calendar.set(year1,month1,day1);
long timeYear1=calendar.getTimeInMillis();
calendar.set(year2,month2,day2);
long timeYear2=calendar.getTimeInMillis();
long 相隔天数=Math.abs((timeYear1-timeYear2)/(1000*60*60*24));
System.out.println(""+year1+"年"+month1+"月"+day1+"日和"+
year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天");
}
}
3.
import java.math.*;
public class ZuoYe4_1{
public static void main(String args[]){
BigInteger chengji=new BigInteger("1"),
ONE=new BigInteger("1"),
i=ONE,
m=new BigInteger("10");
while(https://www.doczj.com/doc/cd13479847.html,pareTo(m)<=0){
chengji=chengji.multiply(i);
i=i.add(ONE);

}
System.out.println(chengji);
}
}

4.
import java.util.*;
public class ZuoYe7_4{
public static void main(String args[]){
HashSet A=new HashSet(),
B=new HashSet(),
tempSet=new HashSet();
A.add(new Integer(1));
A.add(new Integer(2));
A.add(new Integer(3));
A.add(new Integer(4));
B.add(new Integer(1));
B.add(new Integer(3));
B.add(new Integer(7));
B.add(new Integer(9));
B.add(new Integer(11));
tempSet=(HashSet)A.clone();
tempSet.retainAll(B);
System.out.println("交:");
Iterator iter=tempSet.iterator();
while(iter.hasNext()){
Integer te=iter.next();
System.out.printf("%d,",te.intValue());
}
tempSet=(HashSet)A.clone();
tempSet.addAll(B);
iter=tempSet.iterator();
System.out.println("并:");
while(iter.hasNext()){
Integer te=iter.next();
System.out.printf("%d,",te.intValue());
}
tempSet=(HashSet)A.clone();
tempSet.removeAll(B);
System.out.println("差:");
iter=tempSet.iterator();
while(iter.hasNext()){
Integer te=iter.next();
System.out.printf("%d,",te.intValue());
}
}
}
5.
import java.util.*;
class MyKey implements Comparable{
double number=0;
MyKey(double number){
this.number=number;
}
public int compareTo(Object b){
MyKey st=(MyKey)b;
if((this.number-st.number)==0){
return -1;
}
else{
return (int)((this.number-st.number)*1000);
}
}
}
class 硬盘{
int size;
double price;
硬盘(int n, double p){

size=n;
price=p;
}
}
public class ZuoYe4_1{
public static void main(String args[ ]){
int [] size={10,3,7,12,10,22,100,4,6,2};
double [] price={1.2,9.56,2.4,9.3,16.77,12.66,7.4,5.5,5.6,8.9,1.9};
硬盘 [] s=new 硬盘[10];
for(int i=0;is[i]=new 硬盘(size[i],price[i]);
TreeMap treemap=new TreeMap();
for(int i=0;itreemap.put(new MyKey(s[i].size),s[i]);
int number=treemap.size();
System.out.println("树映射中有"+number+"个对象:");
Collection<硬盘> collection=treemap.values();
Iterator<硬盘> iter=collection.iterator();
while(iter.hasNext()){
硬盘 te=iter.next();
System.out.println(te.size+","+te.price);
}
treemap.clear();
for(int i=0;itreemap.put(new MyKey(s[i].price),s[i]);
number=treemap.size();
System.out.println("树映射中有"+number+"个对象:");
collection=treemap.values();
iter=collection.iterator();
while(iter.hasNext()){
硬盘 te=iter.next();
System.out.println(te.size+","+te.price);
}
}
}
第八章 作业题
1.属于操作题目,省略
2.参见例子8-2
3.参见例子8-3
4. 参见例子8-10

第九章 作业题
1.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class ZuoYe9_1
{ public static void main(String args[])
{ int b;
byte tom[]=new byte[25];
try{ File f=new File("Example.java");
FileInputStream in=new FileInputStream(f);
while((b=in.read(tom,0,25))!=-1)
{ String s=new String (tom,0,b);
System.out.print(s);
}
in.close();
}
catch(IOException e)
{ System.out.println("File read Error"+e);
}
}
}



2.
import java.io.*;
import java.util.*;
public class ZuoYe9_2{
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
int b;

try{
FileOutputStream writefile=new FileOutputStream("line.txt");
int line=1,n=10;
System.out.println("输入"+n+"行文本,并存入磁盘:");
while(line<=n){
String s=reader.nextLine();
byte buffer[]=s.getBytes();
writefile.write(buffer,0,buffer.length);
line++;
}
writefile.close();
}
catch(IOException e){
System.out.println("Error "+e);
}
}
}
3.
import java.io.*;
public class ZuoYe9_3{
public static void main(String args[ ]){
int n=-1;
CharArrayWriter out=new CharArrayWriter();
for(char c='а';c<='я';c++){
out.write(c)

;
}
CharArrayReader in=new CharArrayReader(out.toCharArray());
try{ while((n=in.read())!=-1){
if(n%2==0){
System.out.printf("\n");
}
System.out.printf("\t位置%d,字符\'%c\'",n,(char)n);
}
}
catch(IOException e){}
}
}
4.
import java.io.*;
import java.util.*;
public class ZuoYe9_4{
public static void main(String args[]){
try{
FileOutputStream fos=new FileOutputStream("jerry.dat");
DataOutputStream out_data=new DataOutputStream(fos);
Scanner reader=new Scanner(System.in);
for(int i=1;i<=10;i++){
int x=reader.nextInt();
out_data.writeInt(x);
}
out_data.close();
}
catch(IOException e){}
try{
FileInputStream fis=new FileInputStream("jerry.dat");
DataInputStream in_data=new DataInputStream(fis);
for(int i=1;i<=10;i++){
int m=in_data.readInt();
System.out.print(" "+m);
}
in_data.close();
}
catch(IOException e){}
}
}

5.

import java.io.*;
import java.util.*;
class Student implements Serializable{
String name ;
int number;
Student(String name,int number){
https://www.doczj.com/doc/cd13479847.html,=name;
this.number=number;
}
}
public class ZuoYe9_5{
public static void main(String args[]){
List list=new LinkedList();
List cloneList=null;
for(int k=1;k<=12;k++)
list.add(new Student("I am "+k,k));

try{ FileOutputStream fileOut=new FileOutputStream("a.txt");
ObjectOutputStream objectOut=new ObjectOutputStream(fileOut);
objectOut.writeObject(list);
FileInputStream fileIn=new FileInputStream("a.txt");
ObjectInputStream objectIn=new ObjectInputStream(fileIn);
cloneList=(List)objectIn.readObject();
}
catch(Exception event){
System.out.println(event);
}

Iterator iter=cloneList.iterator();
while(iter.hasNext())
{
Student te=(Student)iter.next();
System.out.println(te.number+","+https://www.doczj.com/doc/cd13479847.html,);
}

}
}

6.

import java.io.*;
public class ZuoYe9_6
{ public static void main(String args[])
{
File f=new File("Xiti12_6.java");
try{ RandomAccessFile random=new RandomAccessFile(f,"rw");
random.seek(0);
long m=random.length();
while(m>=0)
{ m=m-1;
random.seek(m);
int c=random.readByte();
if(c<=255&&c>=0)
{ System.out.print((char)c);
}
else
{ m=m-1; //一个汉字占2

个字节
random.seek(m);
byte cc[]=new byte[2];
random.readFully(cc);
System.out.print(new String(cc));
}
}
random.close();
}
catch(IOException ee){}
}
}






5.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Xiti8_5
{ public static void main(String args[])
{ ComputerFrame fr=new ComputerFrame();
fr.setTitle("计算");
}
}
class ComputerFrame extends JFrame implements ActionListener
{ JTextField text1,text2,text3;
JButton button1,button2,button3,button4;
JLabel label;
public ComputerFrame()
{setLayout(new FlowLayout());
text1=new JTextField(10);
text2=new JTextField(10);
text3=new JTextField(10);
label=new JLabel(" ",JLabel.CENTER);
label.setBackground(Color.green);
add(text1);
add(label);
add(text2);
add(text3);
button1=new JButton("加");
button2=new JButton("减");
button3=new JButton("乘");
button4=new JButton("除");
add(button1);
add(button2);
add(button3);
add(button4);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
setSize(400,320);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
public void actionPerformed(ActionEvent e)
{ double n;
if(e.getSource()==button1)
{ double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1+n2;
text3.setText(String.valueOf(n));
label.setText("+");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(e.getSource()==button2)
{ double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1-n2;
text3.setText(String.valueOf(n));
label.setText("-");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(e.getSource()==button3)
{double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1*n2;
text3.setText(String.valueOf(n));
label.setText("*");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(e.getSource()==button4)
{double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1/n2;
text3.setText(String.valueOf(n));
label.setText("/");

}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
validate();
}
}
6.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Xiti8_6
{ public static void main(String args[])
{ new WindowPanel();
}
}
class Mypanel extends JPanel implements ActionListener
{ JButton button;
JTextField text;
Mypanel()
{ button=new JButton(" ");
text=new JTextField(12);
add(button);
add(text);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ String name=text.getText();
if(name.length()>0)
button.setText(name);
validate();
}
}
class WindowPanel extends JFrame
{ Mypanel panel1,panel2;
WindowPanel()
{ panel1=new Mypanel();
panel2=new Mypanel();
panel1.setBackground(Color.red);
panel2.setBackground(Color.blue);
add(panel1,BorderLayout.SOUTH);
add(panel2,BorderLayout.NORTH);
setSize(300,320);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
7.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Xiti8_7
{ public static void main(String args[])
{ new WindowColor();
}
}
class WindowColor extends JFrame
{ JButton button;
JTextField text;
JComboBox list;
WindowColor()
{ setLayout(new FlowLayout());
button=new JButton("hello");
button.setBackground(Color.pink);
button.setForeground(new Color(12,26,200));
text=new JTextField("how are you");
text.setBackground(Color.yellow);
text.setForeground(new Color(200,26,20));
list=new JComboBox();
list.addItem("Hello");
list.addItem("Java");
list.setBackground(Color.cyan);
list.setForeground(new Color(100,100,100));
add(list);
add(button);
add(text);
setSize(300,320);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
8.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Xiti8_8
{ public static void main(String args[])
{ MoveFrame f=new MoveFrame();
f.setBounds(12,12,300,300);
f.setVisible(true);
f.setTitle("移动");
f.validate();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MoveFrame extends JFrame implements ActionListener
{ JButton controlButton,movedButton;
public MoveFrame()
{ controlButton=new JButton("单击我运动另一个按钮");
controlButton.addActionListener(this);
movedButton=new JButton();
movedButton.setBackground(new Color(12,200,34));
setLayout(null);
add(controlButton);
add(movedButton);
controlButton.setBounds(10,30,180,30);
movedButton.setBounds(100,

100,20,20);
}
public void actionPerformed(ActionEvent e)
{ int x=movedButton.getBounds().x;
int y=movedButton.getBounds().y;
x=x+5;
y=y+1;
movedButton.setLocation(x,y);
if(x>200)
{ x=100;
y=100;
}
}
}
9.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class E
{ public static void main(String args[])
{ JFrame fr=new JFrame();
fr.add(new LP(),BorderLayout.CENTER);
fr.setVisible(true);
fr.setBounds(12,12,300,300);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.validate();
}
}

class LP extends JLayeredPane implements MouseListener,MouseMotionListener
{ JButton button[];
JTextField text[];
int x,y,a,b,x0,y0;
LP()
{ setLayout(new FlowLayout());
button=new JButton[8];
for(int k=0;k{ button[k]=new JButton("用鼠标拖动我");
add(button[k]);
button[k].addMouseListener(this);
button[k].addMouseMotionListener(this);
}
text=new JTextField[10];
for(int k=0;k{ text[k]=new JTextField("用鼠标拖动我");
text[k].addMouseListener(this);
add(text[k]);
text[k].addMouseMotionListener(this);
}
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e)
{ Component com=null;
com=(Component)e.getSource();
setLayer(com,JLayeredPane.DRAG_LAYER);
a=com.getBounds().x;
b=com.getBounds().y;
x0=e.getX(); //获取鼠标在事件源中的位置坐标
y0=e.getY();
}
public void mouseReleased(MouseEvent e)
{ Component com=null;
com=(Component)e.getSource();
setLayer(com,JLayeredPane.DEFAULT_LAYER);
Component component[]=this.getComponents();
for(int k=0;k{ Rectangle rect1=component[k].getBounds();
Rectangle rect2=com.getBounds();
if(rect1.intersects(rect2)&&com!=component[k])
{ component[k].setVisible(false);//this.remove(component[k]);
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e)
{ Component com=null;
if(e.getSource() instanceof Component)
{ com=(Component)e.getSource();
a=com.getBounds().x;
b=com.getBounds().y;
x=e.getX(); //获取鼠标在事件源中的位置坐标
y=e.getY();
a=a+x;
b=b+y;
com.setLocation(a-x0,b-y0);
}
}
}
10.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class E
{ public static void main(St

ring args[])
{ JFrame fr=new JFrame();
fr.add(new MoveButton(),BorderLayout.CENTER);
fr.setVisible(true);
fr.setBounds(12,12,300,300);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.validate();
}
}
class MoveButton extends JLayeredPane implements KeyListener
{ JButton b[]=new JButton[8];
int x,y;
MoveButton()
{ setLayout(new FlowLayout());
for(int i=0;i<8;i++)
{ b[i]=new JButton(""+i);
b[i].addKeyListener(this);
add(b[i]);
}
}
public void keyPressed(KeyEvent e)
{ int moveDistance=1;
Component com=(Component)e.getSource();
int x=(int)com.getBounds().x;
int y=(int)com.getBounds().y;
Component component[]=this.getComponents();
if(e.getKeyCode()==KeyEvent.VK_UP)
{ y=y-moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=component[k].getBounds();
if(comRect.intersects(orthRect)&&com!=component[k])
{ y=y+moveDistance;
com.setLocation(x,y);
break;
}
}
if(y<=0) y=10;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ y=y+moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=component[k].getBounds();
if(comRect.intersects(orthRect)&&com!=component[k])
{ y=y-moveDistance;
com.setLocation(x,y);
break;
}
}
if(y>=300) y=300;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ x=x-moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=component[k].getBounds();
if(comRect.intersects(orthRect)&&com!=component[k])
{ x=x+moveDistance;
com.setLocation(x,y);
break;
}
}
if(x<=0) x=0;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{ x=x+moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=component[k].getBounds();
if(comRect.intersects(orthRect)&&com!=component[k])
{ x=x-moveDistance;
com.setLocation(x,y);
break;
}
}
if(x>=300) x=300;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}

第十章 作业题
1.
import java.awt.*;
import java.awt

.event.*;
import javax.swing.*;
public class ZuoYe10_1{
public static void main(String args[]){
MathWindow win=new MathWindow();
}
}
class MathWindow extends JFrame{
JTextField inputText;
JButton button;
MathWindow(){
inputText=new JTextField(10);
button=new JButton("hello");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
inputText.setText(button.getText());
}
});
setLayout(new FlowLayout());
add(inputText);
add(button);
setBounds(100,100,260,190);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
2.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ZuoYe10_2{
public static void main(String args[]){
MathWindow win=new MathWindow();
}
}
class MathWindow extends JFrame implements ActionListener{
JTextField inputText,showUnicode;
JButton button;
MathWindow(){
inputText=new JTextField(10);
showUnicode=new JTextField(10);
button=new JButton("enter");
button.addActionListener(this);
inputText.addActionListener(this);
setLayout(new FlowLayout());
add(inputText);
add(button);
add(showUnicode);
setBounds(100,100,260,190);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
String s=inputText.getText();
StringBuffer str=new StringBuffer();
for(int i=0;ichar c=s.charAt(i);
str.append((int)c);
str.append(",");
}
showUnicode.setText(new String(str));
}
}
3.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ZuoYe10_3{
public static void main(String args[])
{ ComputerFrame fr=new ComputerFrame();
fr.setTitle("计算");
}
}
class ComputerFrame extends JFrame implements ActionListener{
JTextField text1,text2,text3;
JButton button1,button2,button3,button4;
JLabel label;
public ComputerFrame(){
setLayout(new FlowLayout());
text1=new JTextField(10);
text2=new JTextField(10);
text3=new JTextField(10);
label=new JLabel(" ",JLabel.CENTER);
label.setBackground(Color.green);
add(text1);
add(label);
add(text2);
add(text3);
button1=new JButton("加");
button2=new JButton("减");
button3=new JButton("乘");
button4=new JButton("除");
add(button1);
add(button2);
add(button3);
add(button4);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);


button4.addActionListener(this);
setSize(300,320);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
validate();
}
public void actionPerformed(ActionEvent e)
{ double n;
if(e.getSource()==button1)
{ double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1+n2;
text3.setText(String.valueOf(n));
label.setText("+");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(e.getSource()==button2)
{ double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1-n2;
text3.setText(String.valueOf(n));
label.setText("-");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(e.getSource()==button3)
{double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1*n2;
text3.setText(String.valueOf(n));
label.setText("*");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(e.getSource()==button4)
{double n1,n2;
try{ n1=Double.parseDouble(text1.getText());
n2=Double.parseDouble(text2.getText());
n=n1/n2;
text3.setText(String.valueOf(n));
label.setText("/");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
validate();
}
}
4.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class ZuoYe10_4{
public static void main(String args[]){
new ReadFileWindow();
}
}
class ReadFileWindow extends JFrame implements ActionListener{
JMenuBar menubar;
JMenu menu;
JMenuItem openFile;
JTextArea showText;
ReadFileWindow(){
menubar=new JMenuBar();
menu=new JMenu("文件");
openFile=new JMenuItem("打开文件");
menu.add(openFile);
menubar.add(menu);
setJMenuBar(menubar);
showText=new JTextArea(12,12);
add(new JScrollPane(showText));
validate();
openFile.addActionListener(this);
setBounds(120,120,500,370);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
String fileName="hello.txt";
File readFile=new File(fileName);
showText.setText(null);

try{ FileReader inOne=new FileReader(readFile);
BufferedReader inTwo= new BufferedReader(inOne);
String s=null;
int i=0;
while((s=inTwo.readLine())!=null)
showText.append("\n"+s);
inOne.close();
inTwo.close();
}
catch(IOException ex){
showText.setText(ex.toString());
}
}
}

5.

import javax.swing.*;
import java.util.StringTokenizer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ZuoYe10_5
{ public static void main(String args[])
{ ComputerFrame fr=new ComputerFrame();
fr.setTitle("计算的窗口");
}
}
class ComputerFrame extends JFrame implements DocumentListener
{ JTextArea text1,text2;
int count=1;
double sum=0,aver=0;
public ComputerFrame()
{ setLayout(new FlowLayout());
text1=new JTextArea(6,20);
text2=new JTextArea(6,20);
add(new JScrollPane(text1));
add(new JScrollPane(text2));
text2.setEditable(false);
(text1.getDocument()).addDocumentListener(this);
setSize(300,320);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
validate();
}
public void changedUpdate(DocumentEvent e){ //接口方法
hangdleText(); //调用后面的hangdleText()方法
}
public void removeUpdate(DocumentEvent e){ //接口方法
changedUpdate(e);
}
public void insertUpdate(DocumentEvent e){ //接口方法
changedUpdate(e);
}

public void hangdleText(){
String s=text1.getText();
sum=0;
aver=0;
StringTokenizer fenxi=new StringTokenizer(s," ,'\n'");
int n=fenxi.countTokens();
count=n;
double a[]=new double[n];
for(int i=0;i<=n-1;i++)
{ String temp=fenxi.nextToken();
try { a[i]=Double.parseDouble(temp);
sum=sum+a[i];
}
catch(Exception ee)
{ count--;
}
}
aver=sum/count;
text2.setText(null);
text2.append("\n和:"+sum);
text2.append("\n平均值:"+aver);
}
}
6. 参考例子10-14
7.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ZuoYe4_1{
public static void main(String args[]){
Win win=new Win();
}
}
class Win extends JFrame implements KeyListener{
JButton b[]=new JButton[8];
int x,y;
Win(){
setLayout(new FlowLayout());
for(int i=0;i<8;i++) {
b[i]=new JButton(""+i);
b[i].addKeyListener(this);
add(b[i]);
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent

e){
System.exit(0);
}
});
setBounds(10,10,300,300);
setVisible(true);
validate();
}
public void keyPressed(KeyEvent e){
int moveDistance=1;
Component com=(Component)e.getSource();
int x=(int)com.getBounds().x;
int y=(int)com.getBounds().y;
if(e.getKeyCode()==KeyEvent.VK_UP)
{
y=y-moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=b[k].getBounds();
if(comRect.intersects(orthRect)&&com!=b[k])
{ y=y+moveDistance;
com.setLocation(x,y);
break;
}
}
if(y<=0) y=10;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ y=y+moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=b[k].getBounds();
if(comRect.intersects(orthRect)&&com!=b[k])
{ y=y-moveDistance;
com.setLocation(x,y);
break;
}
}
if(y>=300) y=300;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ x=x-moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=b[k].getBounds();
if(comRect.intersects(orthRect)&&com!=b[k])
{ x=x+moveDistance;
com.setLocation(x,y);
break;
}
}
if(x<=0) x=0;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{ x=x+moveDistance;
com.setLocation(x,y);
Rectangle comRect=com.getBounds();
for(int k=0;k{ Rectangle orthRect=b[k].getBounds();
if(comRect.intersects(orthRect)&&com!=b[k])
{ x=x-moveDistance;
com.setLocation(x,y);
break;
}
}
if(x>=300) x=300;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
8.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class ZuoYe10_8
{ public static void main(String args[])
{ new Dwindow();
}
}

class Dwindow extends JFrame implements ActionListener
{ JTextField inputNumber;
JTextArea show;
Dwindow()
{
inputNumber=new JTextField(22);
inputNumber.addActionListener(this);
show=new JTextArea();
add(inputNumber,BorderLayout.NORTH);
add(show,BorderLayout.CENTER);
setBounds(60,60,300,300);

setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{ boolean boo=false;
if(e.getSource()==inputNumber)
{ String s=inputNumber.getText();
for(int i=0;i{ char c=s.charAt(i);
if(!(Character.isDigit(c)))
boo=true;
}
if(boo==true) //弹出“警告”消息对话框。
{ JOptionPane.showMessageDialog(this,"您输入了非法字符","警告对话框",
JOptionPane.WARNING_MESSAGE);
inputNumber.setText(null);
}
else if(boo==false)
{ int number=Integer.parseInt(s);
if(number>=1000){
int n=JOptionPane.showConfirmDialog(this,"确认保存该数字到文件?","确认对话框",
JOptionPane.YES_NO_OPTION );
if(n==JOptionPane.YES_OPTION)
{ saveNumber(number);
}
else if(n==JOptionPane.NO_OPTION)
{ inputNumber.setText(null);
}

}
else
saveNumber(number);
}
}
}
void saveNumber(int n){
RandomAccessFile out=null;
try{ out=new RandomAccessFile("a.dat","rw");
out.seek(out.length());
out.writeUTF("integer:");
out.writeInt(n);
out.close();
}
catch(Exception e){}


}
}



第十一章 作业题
1.参考例子11-2和11-3
2.参考例子11-6

第十二章 作业题
1.参考例子12-1
2.参考例子12-2

3.参考例子12-3
4.使参考例子12-4。
5.使参考例子12-8
第十三章 作业题
1.
import java.applet.*;import java.awt.*;import java.awt.event.*;
public class ZuoYe13_1 extends Applet implements ActionListener
{ TextField text1,text2,text3;
PoliceMan police;
public void init()
{ text1=new TextField(10);
text2=new TextField(10);
text3=new TextField(10);
police=new PoliceMan(this);
add(text1);add(text2);add(text3);
text1.addActionListener(this);
text1.addActionListener(police);
}
public void actionPerformed(ActionEvent e)
{ String number=e.getActionCommand();
int n=Integer.parseInt(number);
int m=n*n;text2.setText(n+"的平方是:"+m);
}
}
class PoliceMan implements ActionListener
{ Example9_3 a=null;
PoliceMan(Example9_3 a)
{ this.a=a;
}
public void actionPerformed(ActionEvent e)
{ String number=e.getActionCommand();
int n=Integer.parseInt(number);
int m=n*

n*n;a.text3.setText(n+"的立方是:"+m);
}
}

2.
import java.applet.*
import java.awt.*;
import java.awt.event.*;
public class ZuoYe13_2 extends Applet implements MouseListener
{ final int number=38; int count=0;
Image[] card=new Image[number];
public void init()
{ addMouseListener(this);
for(int i=0;i{ card[i]=getImage(getCodeBase(),"jiafei"+i+".jpg");
}
}
public void paint(Graphics g)
{ if((card[count])!=null)
g.drawImage(card[count],10,10,
card[count].getWidth(this),card[count].getHeight(this),this);
}
public void mousePressed(MouseEvent e)
{ count++;
if(count>number)
count=0;
repaint();
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
}

相关主题
文本预览
相关文档 最新文档