2023年6月20日发(作者:)
Java基础教程第3版习题解答
第一章习题1.
James Gosling
2.
需3个步骤:
1) 用文本编辑器编写源文件
2) 使用javac编译源文件,得到字节码文件
3) 应用程序使用解释器运行。
3. path d:jdkbin
classpath =d:;.;
4. B
5. java 和 class
6.
D。
第二章习题
1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。false不是标识符。
2.关键字就是Java语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。不是关键字。class implements interface enum extends abstract。
3.float常量必须用F或f为后缀。double常量用D或d为后缀,但允许省略后缀。
4.一维数组名.length。二维数组名.length。
5. C
6.ADF
7. B
8 【代码2】【代码3】【代码4】
9.B。
10.属于操作题,解答略。
11.3,1
12.
public class E {
public static void main(String args[]) { Systeln((int)'你');
Systeln((int)'我');
Systeln((int)'他');
}
}
13.
public class E {
public static void main (String args[ ]) {
char cStart='α',cEnd='ω';
for(char c=cStart;c<=cEnd;c++)
Syste(" "+c);
}
}
第三章习题1. 110
2.beep!!
3.
public class E {
public static void main (String args[ ]) {
for(charc='а';c<='я';c++){
Syste(" "+c);
}
}
}
4.
public
class Xiti3_4
{ public static void main(String args[])
{ double sum=0,a=1;
int i=1;
while(i<=20)
{ sum=sum+a;
i++;
a=a*i;
}
Systeln("sum="+sum); }
}
5.
public class Xiti5
{ public static void main(String args[])
{ int i,j;
for(j=2;j<=100;j++)
{ for(i=2;i<=j/2;i++)
{ if(j%i==0)
break;
}
if(i>j/2)
{ Syste(" "+j);
}
}
}
}
6.
class Xiti6
{ public static void main(String args[])
{ double sum=0,a=1,i=1;
do { sum=sum+a;
i++;
a=(1.0/i)*a;
}
while(i<=20);
Systeln("使用do-while循环计算的sum="+sum);
for(sum=0,i=1,a=1;i<=20;i++)
{ a=a*(1.0/i);
sum=sum+a;
}
Systeln("使用for循环计算的sum="+sum);
}
}
7.
class Xiti7
{ public static void main(String args[])
{ int sum=0,i,j;
for(i=1;i<=1000;i++) { for(j=1,sum=0;j
{ if(i%j==0)
sum=sum+j;
}
if(sum==i)
Systeln("完数:"+i);
}
}
}
8.
import .*;
public class E {
public static void main (String args[ ]) {
int m,n;
Scanner scaner= new Scanner(Syste);
Systeln("输入正数m回车确认");
m = scanent();
Systeln("输入正数n回车确认");
n = scanent();
int p=m;
int q= n;
int r = m%n;
while(r!=0) {
m = n;
n =r;
r =m%n;
}
Systeln(p+"和"+q+"的最大公约数"+n);
Systeln(p+"和"+q+"的最小公倍数"+(p*q)/n);
}
}
9.
public class E
{ public static void main(String args[])
{ int n=1;
long sum=0;
while(true)
{ sum=sum+n;
n++; if(sum>=8888)
break;
}
Systeln("满足条件的最大整数:"+(n-1));
}
}
第四章习题
1. 用该类创建对象时。
2. 一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即或者是参数的个数不同,或者是参数的类型不同
3. 可以。不可以。
4. 不可以。
5. sum=-100。
6. 27
第五章习题
1.如果子类和父类不在同一个包中,那么,子类继承了父类的protected、public成员变量做为子类的成员变量,并且继承了父类的protected、public方法为子类的方法。如果子类和父类不在同一个包里,子类不能继承父类的友好变量和友好方法。
2.不可以。
3.abstract类。
4. 假设B类是A类子类或间接子类,当我们用子类B创建一个对象,并把这个对象的引用放到A类的对象中时,称这个A类对象是子类对象的上转型对象。
5. D
6.15.0。8.0
7.98.0
12
第六章习题
1.接口中能声明变量吗?
不能
2.接口中能定义非抽象方法吗? 不能
3.什么叫接口的回调?
可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中。那么该接口变量就可以调用被类实现的接口中的方法。
4.请说出E类中Systln的输出结果。
18
15
第7章习题
1.内部类的外嵌类的成员变量在内部类中仍然有效吗?
有效。
2.内部类中的方法也可以调用外嵌类中的方法吗?
可以。
3.内部类的类体中可以声明类变量和类方法吗?
不可以。
4.匿名类一定是内部类吗?
一定是。
5.请说出下列程序的输出结果。
大家好,祝工作顺利!
6.请说出下列程序的输出结果。
p是接口变量
7.请说出下列程序的输出结果。
你好 fine thanks
第8章习题
1.不是。"hello"是。
2.4和3。
3.false和true。
4.负数。
5.是true。
6.3和-1。
7.会发生NumberFormatException异常。
8.
苹果
9 【代码1】:15。【代码2】:abc我们。
10.public class E { public static void main (String args[ ]) {
String s1,s2,t1="ABCDabcd";
s1=erCase();
s2=erCase();
Systeln(s1);
Systeln(s2);
String s3=t(s2);
Systeln(s3);
}
}
11.
public class E {
public static void main (String args[ ]) {
String s="ABCDabcd";
char cStart=t(0);
char cEnd = t(h()-1);
Systeln(cStart);
Systeln(cEnd);
}
}
12. import .*;
public class E {
public static void main (String args[ ]) {
int year1,month1,day1,year2,month2,day2;
try{ year1=IntegInt(args[0]);
month1=IntegInt(args[1]);
day1=IntegInt(args[2]);
year2=IntegInt(args[3]);
month2=IntegInt(args[4]);
day2=IntegInt(args[5]);
}
catch(NumberFormatException e)
{ year1=2012;
month1=0;
day1=1;
year2=2018;
month2=0;
day2=1;
}
Calendar calendar=Calenstance();
calen(year1,month1-1,day1);
long timeYear1=calenmeInMillis();
calen(year2,month2-1,day2);
long timeYear2=calenmeInMillis();
long 相隔天数=((timeYear1-timeYear2)/(1000*60*60*24)); Systeln(""+year1+"年"+month1+"月"+day1+"日和"+
year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天");
}
}
13.
import .*;
public class E {
public static void main (String args[ ]) {
double a=0,b=0,c=0;
a=12;
b=24;
c=(0.56);
Systeln(c);
c=(3.14);
Systeln(c);
c=(1);
Systeln(c);
c=(8);
Systeln(c);
}
}
14.
import .*;
public class E {
public static void main(String args[]) {
String cost = "数学87分,物理76分,英语96分";
Scanner scanner = new Scanner(cost);
scannlimiter("[^0123456789.]+");
double sum=0;
int count =0;
while(scannxt()){
try{ double score = scannouble();
count++;
sum = sum+score;
Systeln(score);
}
catch(InputMismatchException exp){
String t = scann();
}
}
Systeln("总分:"+sum+"分");
Systeln("平均分:"+sum/count+"分");
}
} 第9章习题
1.使用FileInputStream。
2.FileInputStream按字节读取文件,FileReader按字符读取文件。
3.不可以。
4.使用对象流写入或读入对象时,要保证对象是序列化的。
5.
import .*;
public class E {
public static void main(String args[]) {
File f=new File("");;
try{ RandomAccessFile random=new RandomAccessFile(f,"rw");
rando(0);
long m=randoh();
while(m>=0) {
m=m-1;
rando(m);
int c=randoyte();
if(c<=255&&c>=0)
Syste((char)c);
else {
m=m-1;
rando(m);
byte cc[]=new byte[2];
randoully(cc);
Syste(new String(cc));
}
}
}
catch(Exception exp){}
}
}
6.
import .*;
public class E {
public static void main(String args[ ]) {
File file=new File("");
File tempFile=new File("");
try{ FileReader inOne=new FileReader(file);
BufferedReader inTwo= new BufferedReader(inOne);
FileWriter tofile=new FileWriter(tempFile);
BufferedWriter out= new BufferedWriter(tofile); String s=null;
int i=0;
s=inTwo.readLine();
while(s!=null) {
i++;
(i+" "+s);
ne();
s=inTwo.readLine();
}
inOne.close();
inTwo.close();
();
();
tofil();
}
catch(IOException e){}
}
}
7 属于操作题,解答略
第10章习题
1.(1)添加数据源,(2)选择驱动程序,(3)命名数据源名称。
2.不必使用数据库名称。
3.事务由一组SQL语句组成,所谓事务处理是指:应用程序保证事务中的SQL语句要么全部都执行,要么一个都不执行。
4.
import .*;
import .*;
public class E {
public static void main(String args[]) {
Query query=new Query();
String dataSource="myData";
String tableName="goods";
Scanner read=new Scanner(Syste);
Syste("输入数据源名:");
dataSource = ine();
Syste("输入表名:");
tableName = ine();
query.setDatasourceName(dataSource);
query.setTableName(tableName);
query.setSQL("SELECT * FROM "+tableName); query.inputQueryResult();
}
}
class Query {
String datasourceName=""; //数据源名
String tableName=""; //表名
String SQL; //SQL语句
public Query() {
try{ Class.forName("dbcDriver");
}
catch(ClassNotFoundException e) {
Syste(e);
}
}
public void setDatasourceName(String s) {
datasourceName = ();
}
public void setTableName(String s) {
tableName = ();
}
public void setSQL(String SQL) {
= ();
}
public void inputQueryResult() {
Connection con;
Statement sql;
ResultSet rs;
try {
String uri = "jdbc:odbc:"+datasourceName;
String id = "";
String password = "";
con = DriverManannection(uri,id,password);
DatabaseMetaData metadata = taData();
ResultSet rs1 = metadlumns(null,null,tableName,null);
int 字段个数 = 0;
while(()) {
字段个数++;
}
sql = eStatement();
rs = teQuery(SQL);
while(()) {
for(int k=1;k<=字段个数;k++) {
Syste(" "+ring(k)+" ");
} Systeln("");
}
();
}
catch(SQLException e) {
Systeln("请输入正确的表名"+e);
}
}
}
5.
import .*;
import .*;
public class E {
public static void main(String args[]) {
Query query = new Query();
String dataSource = "myData";
String tableName = "goods";
query.setDatasourceName(dataSource);
query.setTableName(tableName);
String name = "";
Scanner read=new Scanner(Syste);
Syste("商品名:");
name = ine();
String str="'%["+name+"]%'";
String SQL = "SELECT * FROM "+tableName+" WHERE name LIKE "+str;
query.setSQL(SQL);
Systeln(tableName+"表中商品名是"+name+"的记录");
query.inputQueryResult();
}
}
class Query {
String datasourceName=""; //数据源名
String tableName=""; //表名
String SQL; //SQL语句
public Query() {
try{ Class.forName("dbcDriver");
}
catch(ClassNotFoundException e) {
Syste(e);
} }
public void setDatasourceName(String s) {
datasourceName = ();
}
public void setTableName(String s) {
tableName = ();
}
public void setSQL(String SQL) {
= ();
}
public void inputQueryResult() {
Connection con;
Statement sql;
ResultSet rs;
try {
String uri = "jdbc:odbc:"+datasourceName;
String id = "";
String password = "";
con = DriverManannection(uri,id,password);
DatabaseMetaData metadata = taData();
ResultSet rs1 = metadlumns(null,null,tableName,null);
int 字段个数 = 0;
while(()) {
字段个数++;
}
sql = eStatement();
rs = teQuery(SQL);
while(()) {
for(int k=1;k<=字段个数;k++) {
Syste(" "+ring(k)+" ");
}
Systeln("");
}
();
}
catch(SQLException e) {
Systeln("请输入正确的表名"+e);
}
} }
第11章习题
1.Frame容器的默认布局是BorderLayout布局,Panel容器的默认布局是FlowLayout布局。
2.不可以
3.
import .*;
import javax.swing.event.*;
import javax.swing.*;
import .*;
public class E {
public static void main(String args[]) {
Computer fr=new Computer();
}
}
class Computer extends JFrame implements DocumentListener {
JTextArea text1,text2;
int count=1;
double sum=0,aver=0;
Computer() {
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);
validate();
setDefaultCloseOperation(JFramSE_ON_CLOSE);
}
public void changedUpdate(DocumentEvent e) {
String s=text1.getText();
String []a =("[^0123456789.]+");
sum=0;
aver=0;
for(int i=0;i<h;i++) {
try { sum=sum+DoublDouble(a[i]);
}
catch(Exception ee) {} }
aver=sum/count;
text2.setText(null);
text2.append("n和:"+sum);
text2.append("n平均值:"+aver);
}
public void removeUpdate(DocumentEvent e){
changedUpdate(e);
}
public void insertUpdate(DocumentEvent e){
changedUpdate(e);
}
}
4.
import .*;
import javax.swing.event.*;
import javax.swing.*;
import .*;
public class E {
public static void main(String args[]) {
ComputerFrame fr=new ComputerFrame();
}
}
class ComputerFrame extends JFrame implements ActionListener {
JTextField text1,text2,text3;
JButton buttonAdd,buttonSub,buttonMul,buttonDiv;
JLabel label;
public ComputerFrame() {
setLayout(new FlowLayout());
text1=new JTextField(10);
text2=new JTextField(10);
text3=new JTextField(10);
label=new JLabel(" ",JLabeR);
label.setBackground(Color.green);
add(text1);
add(label);
add(text2);
add(text3);
buttonAdd=new JButton("加");
buttonSub=new JButton("减");
buttonMul=new JButton("乘");
buttonDiv=new JButton("除");
add(buttonAdd);
add(buttonSub); add(buttonMul);
add(buttonDiv);
buttotionListener(this);
buttotionListener(this);
buttotionListener(this);
buttotionListener(this);
setSize(300,320);
setVisible(true);
validate();
setDefaultCloseOperation(JFramSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
double n;
if(urce()==buttonAdd) {
double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1+n2;
text3.setText(StrinOf(n));
label.setText("+");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(urce()==buttonSub) {
double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1-n2;
text3.setText(StrinOf(n));
label.setText("-");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(urce()==buttonMul)
{double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1*n2;
text3.setText(StrinOf(n));
label.setText("*"); }
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(urce()==buttonDiv)
{double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1/n2;
text3.setText(StrinOf(n));
label.setText("/");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
validate();
}
}
5.
3. import .*;
import .*;
import javax.swing.*;
public class E {
public static void main(String args[]){
Window win = new Window();
tle("使用MVC结构");
unds(100,100,420,260);
}
}
class Window extends JFrame implements ActionListener {
Lader lader; //模型
JTextField textAbove,textBottom,textHeight; //视图
JTextArea showArea; //视图
JButton controlButton; //控制器
Window() {
init();
setVisible(true);
setDefaultCloseOperation(JFram_ON_CLOSE);
}
void init() { lader = new Lader();
textAbove = new JTextField(5);
textBottom = new JTextField(5);
textHeight = new JTextField(5);
showArea = new JTextArea();
controlButton=new JButton("计算面积");
JPanel pNorth=new JPanel();
pNort(new JLabel("上底:"));
pNort(textAbove);
pNort(new JLabel("下底:"));
pNort(textBottom);
pNort(new JLabel("高:"));
pNort(textHeight);
pNort(controlButton);
controlButtionListener(this);
add(pNorth,BorderLayo);
add(new JScrollPane(showArea),BorderLayoR);
}
public void actionPerformed(ActionEvent e) {
try{
double above = DoublDouble(textAxt().trim());
double bottom = DoublDouble(textBottom.getText().trim());
double height = DoublDouble(textHeight.getText().trim());
lader.setAbove(above) ;
lader.setBottom(bottom);
lader.setHeight(height);
double area = lader.getArea();
showAd("面积:"+area+"n");
}
catch(Exception ex) {
showAd("n"+ex+"n");
}
}
}
class Lader {
double above,bottom,height;
public double getArea() {
double area = (above+bottom)*height/2.0;
return area;
}
public void setAbove(double a) {
above = a;
}
public void setBottom(double b) { bottom = b;
}
public void setHeight(double c) {
height = c;
}
}
第12章习题
1.2个参数。
2.6个参数。
3.7个参数。
4.(1)创建AffineTransform对象,(2)进行旋转操作,(3)绘制旋转的图形。
5. import .*;
import javax.swing.*;
class MyCanvas extends Canvas {
static int pointX[]=new int[5],
pointY[]=new int[5];
public void paint(Graphics g) {
late(200,200) ; //进行坐标变换将新的坐标,原点设置为(200,200)。
pointX[0]=0;
pointY[0]=-120;
double arcAngle=(72*)/180;
for(int i=1;i<5;i++) {
pointX[i]=(int)(pointX[i-1]*(arcAngle)-pointY[i-1]*(arcAngle));
pointY[i]=(int)(pointY[i-1]*(arcAngle)+pointX[i-1]*(arcAngle));
}
lor(Color.red);
int starX[]={pointX[0],pointX[2],pointX[4],pointX[1],pointX[3],pointX[0]};
int starY[]={pointY[0],pointY[2],pointY[4],pointY[1],pointY[3],pointY[0]};
olygon(starX,starY,6);
}
}
public class E {
public static void main(String args[]) {
JFrame f=new JFrame();
ze(500,450); sible(true);
MyCanvas canvas=new MyCanvas();
(canvas,"Center");
ate();
faultCloseOperation(JFramSE_ON_CLOSE);
}
}
6. import .*;
import javax.swing.*;
import .*;
class MyCanvas extends Canvas {
public void paint(Graphics g) {
lor(Color.red) ;
Graphics2D g_2d=(Graphics2D)g;
QuadCurve2D quadCurve=
new QuadCurve2e(2,10,51,90,100,10);
g_(quadCurve);
quadCrve(2,100,51,10,100,100);
g_(quadCurve);
}
}
public class E {
public static void main(String args[]) {
JFrame f=new JFrame();
ze(500,450);
sible(true);
MyCanvas canvas=new MyCanvas();
(canvas,"Center");
ate();
faultCloseOperation(JFramSE_ON_CLOSE);
}
}
第13章习题
1.4种状态:新建、运行、中断和死亡。
2.有4种原因的中断:
JVM将CPU资源从当前线程切换给其他线程,使本线程让出CPU的使用权处于中断状态。
线程使用CPU资源期间,执行了sleep(int millsecond)方法,使当前线程进入休眠状态。sleep(int millsecond)方法是Thread类中的一个类方法,线程一旦执行了sleep(int millsecond)方法,就立刻让出CPU的使用权,使当前线程处于中断状态。经过参数millsecond指定的豪秒数之后,该线程就重新进到线程队列中排队等待CPU资源,以便从中断处继续运行。
线程使用CPU资源期间,执行了wait()方法,使得当前线程进入等待状态。等待状态的线程不会主动进到线程队列中排队等待CPU资源,必须由其他线程调用notify()方法通知它,使得它重新进到线程队列中排队等待CPU资源,以便从中断处继续运行。有关wait、noftify和notifyAll方法将在第7、8节详细讨论。
线程使用CPU资源期间,执行某个操作进入阻塞状态,比如执行读/写操作引起阻塞。进入阻塞状态时线程不能进入排队队列,只有当引起阻塞的原因消除时,线程才重新进到线程队列中排队等待CPU资源,以便从原来中断处开始继续运行。
3.死亡状态,不能再调用start()方法。
4.新建和死亡状态。
5.两种方法:用Thread类或其子类。
6.Java使我们可以创建多个线程,在处理多线程问题时,我们必须注意这样一个问题:当两个或多个线程同时访问同一个变量,并且一个线程需要修改这个变量。我们应对这样的问题作出处理,否则可能发生混乱。
7.当一个线程使用的同步方法中用到某个变量,而此变量又需要其它线程修改后才能符合本线程的需要,那么可以在同步方法中使用wait()方法。使用wait方法可以中断方法的执行,使本线程等待,暂时让出CPU的使用权,并允许其它线程使用这个同步方法。其它线程如果在使用这个同步方法时不需要等待,那么它使用完这个同步方法的同时,应当用notifyAll()方法通知所有的由于使用这个同步方法而处于等待的线程结束等待。
8.【代码】:BA。
9. public class E {
public static void main(String args[]) {
Cinema a=new Cinema();
.start();
();
();
}
}
class TicketSeller //负责卖票的类。
{ int fiveNumber=3,tenNumber=0,twentyNumber=0;
public synchronized void sellTicket(int receiveMoney)
{ if(receiveMoney==5)
{ fiveNumber=fiveNumber+1; Systeln(ThreantThread().getName()+
"给我5元钱,这是您的1张入场卷");
}
else if(receiveMoney==10)
{ while(fiveNumber<1)
{ try { Systeln(ThreantThread().getName()+"靠边等");
wait();
Systeln(ThreantThread().getName()+"结束等待");
}
catch(InterruptedException e) {}
}
fiveNumber=fiveNumber-1;
tenNumber=tenNumber+1;
Systeln(ThreantThread().getName()+
"给我10元钱,找您5元,这是您的1张入场卷");
}
else if(receiveMoney==20)
{ while(fiveNumber<1||tenNumber<1)
{ try { Systeln(ThreantThread().getName()+"靠边等");
wait();
Systeln(ThreantThread().getName()+"结束等待");
}
catch(InterruptedException e) {}
}
fiveNumber=fiveNumber-1;
tenNumber=tenNumber-1;
twentyNumber=twentyNumber+1;
Systeln(ThreantThread().getName()+
"给20元钱,找您一张5元和一张10元,这是您的1张入场卷");
}
notifyAll();
}
}
class Cinema implements Runnable
{ Thread zhang,sun,zhao;
TicketSeller seller;
Cinema()
{ zhang=new Thread(this); sun=new Thread(this);
zhao=new Thread(this);
zhang.setName("张小有");
me("孙大名");
me("赵中堂");
seller=new TicketSeller();
}
public void run()
{ if(ThreantThread()==zhang)
{ selleicket(20);
}
else if(ThreantThread()==sun)
{ selleicket(10);
}
else if(ThreantThread()==zhao)
{ selleicket(5);
}
}
}
第14章习题
1.URL对象调用InputStream openStream()
方法可以返回一个输入流,该输入流指向URL对象所包含的资源。通过该输入流可以将服务器上的资源信息读入到客户端。
2.端口号与IP地址的组合得出一个网络套接字。客户端的套接字和服务器端的套接字通过输入、输出流互相连接后进行通信。
3.使用方法accept(),accept()会返回一个和客户端Socket对象相连接的Socket对象。accept方法会堵塞线程的继续执行,直到接收到客户的呼叫。
4. 域名/IP
5.
(1)客户端
import .*;
import .*;
import .*;
import .*;
import javax.swing.*;
public class Client
{ public static void main(String args[]) { new ComputerClient();
}
}
class ComputerClient extends Frame implements Runnable,ActionListener
{ Button connection,send;
TextField inputText,showResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
ComputerClient()
{ socket=new Socket();
setLayout(new FlowLayout());
Box box=eVerticalBox();
connection=new Button("连接服务器");
send=new Button("发送");
abled(false);
inputText=new TextField(12);
showResult=new TextField(12);
(connection);
(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
(inputText);
(send);
(new Label("收到的结果:"));
(showResult);
connection.addActionListener(this);
tionListener(this);
thread=new Thread(this);
add(box);
setBounds(10,30,300,400);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ Syste(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(urce()==connection)
{ try //请求和服务器建立套接字连接:
{ if(sockenected())
{}
else { InetAddress address=InetAddresName("127.0.0.1");
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
sockect(socketAddress);
in =new DataInputStream(sockeputStream());
out = new DataOutputStream(socketputStream());
abled(true);
threa();
}
}
catch (IOException ee){}
}
if(urce()==send)
{ String s=inputxt();
if(s!=null)
{ try { UTF(s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=TF();
showResult.setText(s);
}
catch(IOException e)
{ showResult.setText("与服务器已断开");
break;
}
}
}
}
(2)服务器端
import .*;
import .*;
import .*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true) { try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ Systeln("正在监听"); //ServerSocket对象不能重复创建
}
try{ Systeln(" 等待客户呼叫");
you=servet();
Systeln("客户的地址:"+etAddress());
}
catch (IOException e)
{ Systeln("正在等待客户");
}
if(you!=null)
{ new Server_thread(you).start(); //为每个客户启动一个专门的线程
}
}
}
}
class Server_thread extends Thread
{ Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
boolean quesion=false;
Server_thread(Socket t)
{ socket=t;
try { out=new DataOutputStream(socketputStream());
in=new DataInputStream(sockeputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;
int i=0;
try{ s=TF();//堵塞状态,除非读取到信息
quesion=false;
StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=DoublOf(temp).doubleValue();i++;
} catch(NumberFormatException e)
{ UTF("请输入数字字符");
quesion=true;
}
}
if(quesion==false)
{ double p=(a[0]+a[1]+a[2])/2.0;
UTF(" "+(p*(p-a[0])*(p-a[1])*(p-a[2])));
}
}
catch (IOException e)
{ Systeln("客户离开");
return;
}
}
}
}
2023年6月20日发(作者:)
Java基础教程第3版习题解答
第一章习题1.
James Gosling
2.
需3个步骤:
1) 用文本编辑器编写源文件
2) 使用javac编译源文件,得到字节码文件
3) 应用程序使用解释器运行。
3. path d:jdkbin
classpath =d:;.;
4. B
5. java 和 class
6.
D。
第二章习题
1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。false不是标识符。
2.关键字就是Java语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。不是关键字。class implements interface enum extends abstract。
3.float常量必须用F或f为后缀。double常量用D或d为后缀,但允许省略后缀。
4.一维数组名.length。二维数组名.length。
5. C
6.ADF
7. B
8 【代码2】【代码3】【代码4】
9.B。
10.属于操作题,解答略。
11.3,1
12.
public class E {
public static void main(String args[]) { Systeln((int)'你');
Systeln((int)'我');
Systeln((int)'他');
}
}
13.
public class E {
public static void main (String args[ ]) {
char cStart='α',cEnd='ω';
for(char c=cStart;c<=cEnd;c++)
Syste(" "+c);
}
}
第三章习题1. 110
2.beep!!
3.
public class E {
public static void main (String args[ ]) {
for(charc='а';c<='я';c++){
Syste(" "+c);
}
}
}
4.
public
class Xiti3_4
{ public static void main(String args[])
{ double sum=0,a=1;
int i=1;
while(i<=20)
{ sum=sum+a;
i++;
a=a*i;
}
Systeln("sum="+sum); }
}
5.
public class Xiti5
{ public static void main(String args[])
{ int i,j;
for(j=2;j<=100;j++)
{ for(i=2;i<=j/2;i++)
{ if(j%i==0)
break;
}
if(i>j/2)
{ Syste(" "+j);
}
}
}
}
6.
class Xiti6
{ public static void main(String args[])
{ double sum=0,a=1,i=1;
do { sum=sum+a;
i++;
a=(1.0/i)*a;
}
while(i<=20);
Systeln("使用do-while循环计算的sum="+sum);
for(sum=0,i=1,a=1;i<=20;i++)
{ a=a*(1.0/i);
sum=sum+a;
}
Systeln("使用for循环计算的sum="+sum);
}
}
7.
class Xiti7
{ public static void main(String args[])
{ int sum=0,i,j;
for(i=1;i<=1000;i++) { for(j=1,sum=0;j
{ if(i%j==0)
sum=sum+j;
}
if(sum==i)
Systeln("完数:"+i);
}
}
}
8.
import .*;
public class E {
public static void main (String args[ ]) {
int m,n;
Scanner scaner= new Scanner(Syste);
Systeln("输入正数m回车确认");
m = scanent();
Systeln("输入正数n回车确认");
n = scanent();
int p=m;
int q= n;
int r = m%n;
while(r!=0) {
m = n;
n =r;
r =m%n;
}
Systeln(p+"和"+q+"的最大公约数"+n);
Systeln(p+"和"+q+"的最小公倍数"+(p*q)/n);
}
}
9.
public class E
{ public static void main(String args[])
{ int n=1;
long sum=0;
while(true)
{ sum=sum+n;
n++; if(sum>=8888)
break;
}
Systeln("满足条件的最大整数:"+(n-1));
}
}
第四章习题
1. 用该类创建对象时。
2. 一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即或者是参数的个数不同,或者是参数的类型不同
3. 可以。不可以。
4. 不可以。
5. sum=-100。
6. 27
第五章习题
1.如果子类和父类不在同一个包中,那么,子类继承了父类的protected、public成员变量做为子类的成员变量,并且继承了父类的protected、public方法为子类的方法。如果子类和父类不在同一个包里,子类不能继承父类的友好变量和友好方法。
2.不可以。
3.abstract类。
4. 假设B类是A类子类或间接子类,当我们用子类B创建一个对象,并把这个对象的引用放到A类的对象中时,称这个A类对象是子类对象的上转型对象。
5. D
6.15.0。8.0
7.98.0
12
第六章习题
1.接口中能声明变量吗?
不能
2.接口中能定义非抽象方法吗? 不能
3.什么叫接口的回调?
可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中。那么该接口变量就可以调用被类实现的接口中的方法。
4.请说出E类中Systln的输出结果。
18
15
第7章习题
1.内部类的外嵌类的成员变量在内部类中仍然有效吗?
有效。
2.内部类中的方法也可以调用外嵌类中的方法吗?
可以。
3.内部类的类体中可以声明类变量和类方法吗?
不可以。
4.匿名类一定是内部类吗?
一定是。
5.请说出下列程序的输出结果。
大家好,祝工作顺利!
6.请说出下列程序的输出结果。
p是接口变量
7.请说出下列程序的输出结果。
你好 fine thanks
第8章习题
1.不是。"hello"是。
2.4和3。
3.false和true。
4.负数。
5.是true。
6.3和-1。
7.会发生NumberFormatException异常。
8.
苹果
9 【代码1】:15。【代码2】:abc我们。
10.public class E { public static void main (String args[ ]) {
String s1,s2,t1="ABCDabcd";
s1=erCase();
s2=erCase();
Systeln(s1);
Systeln(s2);
String s3=t(s2);
Systeln(s3);
}
}
11.
public class E {
public static void main (String args[ ]) {
String s="ABCDabcd";
char cStart=t(0);
char cEnd = t(h()-1);
Systeln(cStart);
Systeln(cEnd);
}
}
12. import .*;
public class E {
public static void main (String args[ ]) {
int year1,month1,day1,year2,month2,day2;
try{ year1=IntegInt(args[0]);
month1=IntegInt(args[1]);
day1=IntegInt(args[2]);
year2=IntegInt(args[3]);
month2=IntegInt(args[4]);
day2=IntegInt(args[5]);
}
catch(NumberFormatException e)
{ year1=2012;
month1=0;
day1=1;
year2=2018;
month2=0;
day2=1;
}
Calendar calendar=Calenstance();
calen(year1,month1-1,day1);
long timeYear1=calenmeInMillis();
calen(year2,month2-1,day2);
long timeYear2=calenmeInMillis();
long 相隔天数=((timeYear1-timeYear2)/(1000*60*60*24)); Systeln(""+year1+"年"+month1+"月"+day1+"日和"+
year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天");
}
}
13.
import .*;
public class E {
public static void main (String args[ ]) {
double a=0,b=0,c=0;
a=12;
b=24;
c=(0.56);
Systeln(c);
c=(3.14);
Systeln(c);
c=(1);
Systeln(c);
c=(8);
Systeln(c);
}
}
14.
import .*;
public class E {
public static void main(String args[]) {
String cost = "数学87分,物理76分,英语96分";
Scanner scanner = new Scanner(cost);
scannlimiter("[^0123456789.]+");
double sum=0;
int count =0;
while(scannxt()){
try{ double score = scannouble();
count++;
sum = sum+score;
Systeln(score);
}
catch(InputMismatchException exp){
String t = scann();
}
}
Systeln("总分:"+sum+"分");
Systeln("平均分:"+sum/count+"分");
}
} 第9章习题
1.使用FileInputStream。
2.FileInputStream按字节读取文件,FileReader按字符读取文件。
3.不可以。
4.使用对象流写入或读入对象时,要保证对象是序列化的。
5.
import .*;
public class E {
public static void main(String args[]) {
File f=new File("");;
try{ RandomAccessFile random=new RandomAccessFile(f,"rw");
rando(0);
long m=randoh();
while(m>=0) {
m=m-1;
rando(m);
int c=randoyte();
if(c<=255&&c>=0)
Syste((char)c);
else {
m=m-1;
rando(m);
byte cc[]=new byte[2];
randoully(cc);
Syste(new String(cc));
}
}
}
catch(Exception exp){}
}
}
6.
import .*;
public class E {
public static void main(String args[ ]) {
File file=new File("");
File tempFile=new File("");
try{ FileReader inOne=new FileReader(file);
BufferedReader inTwo= new BufferedReader(inOne);
FileWriter tofile=new FileWriter(tempFile);
BufferedWriter out= new BufferedWriter(tofile); String s=null;
int i=0;
s=inTwo.readLine();
while(s!=null) {
i++;
(i+" "+s);
ne();
s=inTwo.readLine();
}
inOne.close();
inTwo.close();
();
();
tofil();
}
catch(IOException e){}
}
}
7 属于操作题,解答略
第10章习题
1.(1)添加数据源,(2)选择驱动程序,(3)命名数据源名称。
2.不必使用数据库名称。
3.事务由一组SQL语句组成,所谓事务处理是指:应用程序保证事务中的SQL语句要么全部都执行,要么一个都不执行。
4.
import .*;
import .*;
public class E {
public static void main(String args[]) {
Query query=new Query();
String dataSource="myData";
String tableName="goods";
Scanner read=new Scanner(Syste);
Syste("输入数据源名:");
dataSource = ine();
Syste("输入表名:");
tableName = ine();
query.setDatasourceName(dataSource);
query.setTableName(tableName);
query.setSQL("SELECT * FROM "+tableName); query.inputQueryResult();
}
}
class Query {
String datasourceName=""; //数据源名
String tableName=""; //表名
String SQL; //SQL语句
public Query() {
try{ Class.forName("dbcDriver");
}
catch(ClassNotFoundException e) {
Syste(e);
}
}
public void setDatasourceName(String s) {
datasourceName = ();
}
public void setTableName(String s) {
tableName = ();
}
public void setSQL(String SQL) {
= ();
}
public void inputQueryResult() {
Connection con;
Statement sql;
ResultSet rs;
try {
String uri = "jdbc:odbc:"+datasourceName;
String id = "";
String password = "";
con = DriverManannection(uri,id,password);
DatabaseMetaData metadata = taData();
ResultSet rs1 = metadlumns(null,null,tableName,null);
int 字段个数 = 0;
while(()) {
字段个数++;
}
sql = eStatement();
rs = teQuery(SQL);
while(()) {
for(int k=1;k<=字段个数;k++) {
Syste(" "+ring(k)+" ");
} Systeln("");
}
();
}
catch(SQLException e) {
Systeln("请输入正确的表名"+e);
}
}
}
5.
import .*;
import .*;
public class E {
public static void main(String args[]) {
Query query = new Query();
String dataSource = "myData";
String tableName = "goods";
query.setDatasourceName(dataSource);
query.setTableName(tableName);
String name = "";
Scanner read=new Scanner(Syste);
Syste("商品名:");
name = ine();
String str="'%["+name+"]%'";
String SQL = "SELECT * FROM "+tableName+" WHERE name LIKE "+str;
query.setSQL(SQL);
Systeln(tableName+"表中商品名是"+name+"的记录");
query.inputQueryResult();
}
}
class Query {
String datasourceName=""; //数据源名
String tableName=""; //表名
String SQL; //SQL语句
public Query() {
try{ Class.forName("dbcDriver");
}
catch(ClassNotFoundException e) {
Syste(e);
} }
public void setDatasourceName(String s) {
datasourceName = ();
}
public void setTableName(String s) {
tableName = ();
}
public void setSQL(String SQL) {
= ();
}
public void inputQueryResult() {
Connection con;
Statement sql;
ResultSet rs;
try {
String uri = "jdbc:odbc:"+datasourceName;
String id = "";
String password = "";
con = DriverManannection(uri,id,password);
DatabaseMetaData metadata = taData();
ResultSet rs1 = metadlumns(null,null,tableName,null);
int 字段个数 = 0;
while(()) {
字段个数++;
}
sql = eStatement();
rs = teQuery(SQL);
while(()) {
for(int k=1;k<=字段个数;k++) {
Syste(" "+ring(k)+" ");
}
Systeln("");
}
();
}
catch(SQLException e) {
Systeln("请输入正确的表名"+e);
}
} }
第11章习题
1.Frame容器的默认布局是BorderLayout布局,Panel容器的默认布局是FlowLayout布局。
2.不可以
3.
import .*;
import javax.swing.event.*;
import javax.swing.*;
import .*;
public class E {
public static void main(String args[]) {
Computer fr=new Computer();
}
}
class Computer extends JFrame implements DocumentListener {
JTextArea text1,text2;
int count=1;
double sum=0,aver=0;
Computer() {
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);
validate();
setDefaultCloseOperation(JFramSE_ON_CLOSE);
}
public void changedUpdate(DocumentEvent e) {
String s=text1.getText();
String []a =("[^0123456789.]+");
sum=0;
aver=0;
for(int i=0;i<h;i++) {
try { sum=sum+DoublDouble(a[i]);
}
catch(Exception ee) {} }
aver=sum/count;
text2.setText(null);
text2.append("n和:"+sum);
text2.append("n平均值:"+aver);
}
public void removeUpdate(DocumentEvent e){
changedUpdate(e);
}
public void insertUpdate(DocumentEvent e){
changedUpdate(e);
}
}
4.
import .*;
import javax.swing.event.*;
import javax.swing.*;
import .*;
public class E {
public static void main(String args[]) {
ComputerFrame fr=new ComputerFrame();
}
}
class ComputerFrame extends JFrame implements ActionListener {
JTextField text1,text2,text3;
JButton buttonAdd,buttonSub,buttonMul,buttonDiv;
JLabel label;
public ComputerFrame() {
setLayout(new FlowLayout());
text1=new JTextField(10);
text2=new JTextField(10);
text3=new JTextField(10);
label=new JLabel(" ",JLabeR);
label.setBackground(Color.green);
add(text1);
add(label);
add(text2);
add(text3);
buttonAdd=new JButton("加");
buttonSub=new JButton("减");
buttonMul=new JButton("乘");
buttonDiv=new JButton("除");
add(buttonAdd);
add(buttonSub); add(buttonMul);
add(buttonDiv);
buttotionListener(this);
buttotionListener(this);
buttotionListener(this);
buttotionListener(this);
setSize(300,320);
setVisible(true);
validate();
setDefaultCloseOperation(JFramSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
double n;
if(urce()==buttonAdd) {
double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1+n2;
text3.setText(StrinOf(n));
label.setText("+");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(urce()==buttonSub) {
double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1-n2;
text3.setText(StrinOf(n));
label.setText("-");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(urce()==buttonMul)
{double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1*n2;
text3.setText(StrinOf(n));
label.setText("*"); }
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
else if(urce()==buttonDiv)
{double n1,n2;
try{ n1=DoublDouble(text1.getText());
n2=DoublDouble(text2.getText());
n=n1/n2;
text3.setText(StrinOf(n));
label.setText("/");
}
catch(NumberFormatException ee)
{ text3.setText("请输入数字字符");
}
}
validate();
}
}
5.
3. import .*;
import .*;
import javax.swing.*;
public class E {
public static void main(String args[]){
Window win = new Window();
tle("使用MVC结构");
unds(100,100,420,260);
}
}
class Window extends JFrame implements ActionListener {
Lader lader; //模型
JTextField textAbove,textBottom,textHeight; //视图
JTextArea showArea; //视图
JButton controlButton; //控制器
Window() {
init();
setVisible(true);
setDefaultCloseOperation(JFram_ON_CLOSE);
}
void init() { lader = new Lader();
textAbove = new JTextField(5);
textBottom = new JTextField(5);
textHeight = new JTextField(5);
showArea = new JTextArea();
controlButton=new JButton("计算面积");
JPanel pNorth=new JPanel();
pNort(new JLabel("上底:"));
pNort(textAbove);
pNort(new JLabel("下底:"));
pNort(textBottom);
pNort(new JLabel("高:"));
pNort(textHeight);
pNort(controlButton);
controlButtionListener(this);
add(pNorth,BorderLayo);
add(new JScrollPane(showArea),BorderLayoR);
}
public void actionPerformed(ActionEvent e) {
try{
double above = DoublDouble(textAxt().trim());
double bottom = DoublDouble(textBottom.getText().trim());
double height = DoublDouble(textHeight.getText().trim());
lader.setAbove(above) ;
lader.setBottom(bottom);
lader.setHeight(height);
double area = lader.getArea();
showAd("面积:"+area+"n");
}
catch(Exception ex) {
showAd("n"+ex+"n");
}
}
}
class Lader {
double above,bottom,height;
public double getArea() {
double area = (above+bottom)*height/2.0;
return area;
}
public void setAbove(double a) {
above = a;
}
public void setBottom(double b) { bottom = b;
}
public void setHeight(double c) {
height = c;
}
}
第12章习题
1.2个参数。
2.6个参数。
3.7个参数。
4.(1)创建AffineTransform对象,(2)进行旋转操作,(3)绘制旋转的图形。
5. import .*;
import javax.swing.*;
class MyCanvas extends Canvas {
static int pointX[]=new int[5],
pointY[]=new int[5];
public void paint(Graphics g) {
late(200,200) ; //进行坐标变换将新的坐标,原点设置为(200,200)。
pointX[0]=0;
pointY[0]=-120;
double arcAngle=(72*)/180;
for(int i=1;i<5;i++) {
pointX[i]=(int)(pointX[i-1]*(arcAngle)-pointY[i-1]*(arcAngle));
pointY[i]=(int)(pointY[i-1]*(arcAngle)+pointX[i-1]*(arcAngle));
}
lor(Color.red);
int starX[]={pointX[0],pointX[2],pointX[4],pointX[1],pointX[3],pointX[0]};
int starY[]={pointY[0],pointY[2],pointY[4],pointY[1],pointY[3],pointY[0]};
olygon(starX,starY,6);
}
}
public class E {
public static void main(String args[]) {
JFrame f=new JFrame();
ze(500,450); sible(true);
MyCanvas canvas=new MyCanvas();
(canvas,"Center");
ate();
faultCloseOperation(JFramSE_ON_CLOSE);
}
}
6. import .*;
import javax.swing.*;
import .*;
class MyCanvas extends Canvas {
public void paint(Graphics g) {
lor(Color.red) ;
Graphics2D g_2d=(Graphics2D)g;
QuadCurve2D quadCurve=
new QuadCurve2e(2,10,51,90,100,10);
g_(quadCurve);
quadCrve(2,100,51,10,100,100);
g_(quadCurve);
}
}
public class E {
public static void main(String args[]) {
JFrame f=new JFrame();
ze(500,450);
sible(true);
MyCanvas canvas=new MyCanvas();
(canvas,"Center");
ate();
faultCloseOperation(JFramSE_ON_CLOSE);
}
}
第13章习题
1.4种状态:新建、运行、中断和死亡。
2.有4种原因的中断:
JVM将CPU资源从当前线程切换给其他线程,使本线程让出CPU的使用权处于中断状态。
线程使用CPU资源期间,执行了sleep(int millsecond)方法,使当前线程进入休眠状态。sleep(int millsecond)方法是Thread类中的一个类方法,线程一旦执行了sleep(int millsecond)方法,就立刻让出CPU的使用权,使当前线程处于中断状态。经过参数millsecond指定的豪秒数之后,该线程就重新进到线程队列中排队等待CPU资源,以便从中断处继续运行。
线程使用CPU资源期间,执行了wait()方法,使得当前线程进入等待状态。等待状态的线程不会主动进到线程队列中排队等待CPU资源,必须由其他线程调用notify()方法通知它,使得它重新进到线程队列中排队等待CPU资源,以便从中断处继续运行。有关wait、noftify和notifyAll方法将在第7、8节详细讨论。
线程使用CPU资源期间,执行某个操作进入阻塞状态,比如执行读/写操作引起阻塞。进入阻塞状态时线程不能进入排队队列,只有当引起阻塞的原因消除时,线程才重新进到线程队列中排队等待CPU资源,以便从原来中断处开始继续运行。
3.死亡状态,不能再调用start()方法。
4.新建和死亡状态。
5.两种方法:用Thread类或其子类。
6.Java使我们可以创建多个线程,在处理多线程问题时,我们必须注意这样一个问题:当两个或多个线程同时访问同一个变量,并且一个线程需要修改这个变量。我们应对这样的问题作出处理,否则可能发生混乱。
7.当一个线程使用的同步方法中用到某个变量,而此变量又需要其它线程修改后才能符合本线程的需要,那么可以在同步方法中使用wait()方法。使用wait方法可以中断方法的执行,使本线程等待,暂时让出CPU的使用权,并允许其它线程使用这个同步方法。其它线程如果在使用这个同步方法时不需要等待,那么它使用完这个同步方法的同时,应当用notifyAll()方法通知所有的由于使用这个同步方法而处于等待的线程结束等待。
8.【代码】:BA。
9. public class E {
public static void main(String args[]) {
Cinema a=new Cinema();
.start();
();
();
}
}
class TicketSeller //负责卖票的类。
{ int fiveNumber=3,tenNumber=0,twentyNumber=0;
public synchronized void sellTicket(int receiveMoney)
{ if(receiveMoney==5)
{ fiveNumber=fiveNumber+1; Systeln(ThreantThread().getName()+
"给我5元钱,这是您的1张入场卷");
}
else if(receiveMoney==10)
{ while(fiveNumber<1)
{ try { Systeln(ThreantThread().getName()+"靠边等");
wait();
Systeln(ThreantThread().getName()+"结束等待");
}
catch(InterruptedException e) {}
}
fiveNumber=fiveNumber-1;
tenNumber=tenNumber+1;
Systeln(ThreantThread().getName()+
"给我10元钱,找您5元,这是您的1张入场卷");
}
else if(receiveMoney==20)
{ while(fiveNumber<1||tenNumber<1)
{ try { Systeln(ThreantThread().getName()+"靠边等");
wait();
Systeln(ThreantThread().getName()+"结束等待");
}
catch(InterruptedException e) {}
}
fiveNumber=fiveNumber-1;
tenNumber=tenNumber-1;
twentyNumber=twentyNumber+1;
Systeln(ThreantThread().getName()+
"给20元钱,找您一张5元和一张10元,这是您的1张入场卷");
}
notifyAll();
}
}
class Cinema implements Runnable
{ Thread zhang,sun,zhao;
TicketSeller seller;
Cinema()
{ zhang=new Thread(this); sun=new Thread(this);
zhao=new Thread(this);
zhang.setName("张小有");
me("孙大名");
me("赵中堂");
seller=new TicketSeller();
}
public void run()
{ if(ThreantThread()==zhang)
{ selleicket(20);
}
else if(ThreantThread()==sun)
{ selleicket(10);
}
else if(ThreantThread()==zhao)
{ selleicket(5);
}
}
}
第14章习题
1.URL对象调用InputStream openStream()
方法可以返回一个输入流,该输入流指向URL对象所包含的资源。通过该输入流可以将服务器上的资源信息读入到客户端。
2.端口号与IP地址的组合得出一个网络套接字。客户端的套接字和服务器端的套接字通过输入、输出流互相连接后进行通信。
3.使用方法accept(),accept()会返回一个和客户端Socket对象相连接的Socket对象。accept方法会堵塞线程的继续执行,直到接收到客户的呼叫。
4. 域名/IP
5.
(1)客户端
import .*;
import .*;
import .*;
import .*;
import javax.swing.*;
public class Client
{ public static void main(String args[]) { new ComputerClient();
}
}
class ComputerClient extends Frame implements Runnable,ActionListener
{ Button connection,send;
TextField inputText,showResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
ComputerClient()
{ socket=new Socket();
setLayout(new FlowLayout());
Box box=eVerticalBox();
connection=new Button("连接服务器");
send=new Button("发送");
abled(false);
inputText=new TextField(12);
showResult=new TextField(12);
(connection);
(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
(inputText);
(send);
(new Label("收到的结果:"));
(showResult);
connection.addActionListener(this);
tionListener(this);
thread=new Thread(this);
add(box);
setBounds(10,30,300,400);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ Syste(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(urce()==connection)
{ try //请求和服务器建立套接字连接:
{ if(sockenected())
{}
else { InetAddress address=InetAddresName("127.0.0.1");
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
sockect(socketAddress);
in =new DataInputStream(sockeputStream());
out = new DataOutputStream(socketputStream());
abled(true);
threa();
}
}
catch (IOException ee){}
}
if(urce()==send)
{ String s=inputxt();
if(s!=null)
{ try { UTF(s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=TF();
showResult.setText(s);
}
catch(IOException e)
{ showResult.setText("与服务器已断开");
break;
}
}
}
}
(2)服务器端
import .*;
import .*;
import .*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true) { try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ Systeln("正在监听"); //ServerSocket对象不能重复创建
}
try{ Systeln(" 等待客户呼叫");
you=servet();
Systeln("客户的地址:"+etAddress());
}
catch (IOException e)
{ Systeln("正在等待客户");
}
if(you!=null)
{ new Server_thread(you).start(); //为每个客户启动一个专门的线程
}
}
}
}
class Server_thread extends Thread
{ Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
boolean quesion=false;
Server_thread(Socket t)
{ socket=t;
try { out=new DataOutputStream(socketputStream());
in=new DataInputStream(sockeputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;
int i=0;
try{ s=TF();//堵塞状态,除非读取到信息
quesion=false;
StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=DoublOf(temp).doubleValue();i++;
} catch(NumberFormatException e)
{ UTF("请输入数字字符");
quesion=true;
}
}
if(quesion==false)
{ double p=(a[0]+a[1]+a[2])/2.0;
UTF(" "+(p*(p-a[0])*(p-a[1])*(p-a[2])));
}
}
catch (IOException e)
{ Systeln("客户离开");
return;
}
}
}
}
发布评论