java2实用教程第4版 - 习题解答
更新时间:2023-11-12 18:32:01 阅读量: 教育文库 文档下载
- java推荐度:
- 相关推荐
习题解答
习题一(第1章)
一、问答题
1.James Gosling 2.需3个步骤:
1) 用文本编辑器编写源文件。
2) 使用javac编译源文件,得到字节码文件。 3) 使用解释器运行程序。
3.由类所构成,应用程序必须有一个类含有public static void main(String args[])方法,含有该方法的类称为应用程序的主类。不一定,但最多有一个public类。 4.set classpath=D:\\jdk\\jre\\lib\\rt.jar;.; 5. java和class 6. java Bird
7. 独行风格(大括号独占行)和行尾风格(左大扩号在上一行行尾,右大括号独占行) 二、选择题 1.B。2.D。 三、阅读程序 1.(a)Person.java。(b)两个字节码,分别是Person.class和Xiti.class。(c)得到“NoSuchMethodError”,得到“NoClassDefFoundError: Xiti/class”,得到“您好,很高兴认识您 nice to meet you”
习题二(第2章)
一、问答题
1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。false不是标识符。 2.关键字就是Java语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。不是关键字。class implements interface enum extends abstract。 3.boolean,char,byte,short,int,long,float,double。
4.float常量必须用F或f为后缀。double常量用D或d为后缀,但允许省略后缀。 5.一维数组名.length。二维数组名.length。 二、选择题
1.C。2.ADF。3.B。4.BE。5.【代码2】【代码3】【代码4】【代码5】。6.B。
三、阅读或调试程序
1.属于操作题,解答略。 2.属于操作题,解答略。 3.属于操作题,解答略。 4.【代码1】:4。【代码2】:b[0]=1。 5.【代码1】:40。【代码2】:7 四、编写程序 1. public class E {
public static void main(String args[]) { System.out.println((int)'你'); System.out.println((int)'我'); System.out.println((int)'他'); } }
2. public class E {
public static void main (String args[ ]) { char cStart='α',cEnd='ω'; for(char c=cStart;c<=cEnd;c++) System.out.print(\ } }
习题三(第3章)
一、问答题 1.boolean 2.不可以 3.boolean 4. 不是必须的
5.结束while语句的执行 6.可以 二、选择题
1.A。 2.C。 3.C。 三、阅读程序 1.你,苹,甜 2.Jeep好好 3.x=-5,y=-1
四、编程序题
1.public class Xiti1 {
public static void main(String args[]) {
double sum=0,a=1; int i=1; while(i<=10) { sum=sum+a; i++; a=a*i; }
System.out.println(\ } }
2.public class Xiti2 {
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) {
System.out.print(\ } } } }
3.class Xiti3 {
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);
System.out.println(\使用do-while循环计算的sum=\ for(sum=0,i=1,a=1;i<=20;i++) { a=a*(1.0/i); sum=sum+a; }
System.out.println(\使用for循环计算的sum=\ } }
4.public class Xiti4 {
public static void main(String args[]) { int sum=0,i,j; for(i=1;i<=1000;i++) { for(j=1,sum=0;j
System.out.println(\完数:\ } } }
5.public class Xiti5 {
public static void main(String args[]) { int m=8,item=m,i=1; long sum=0;
for(i=1,sum=0,item=m;i<=10;i++) { sum=sum+item; item=item*10+m; }
System.out.println(sum); } }
6. public class Xiti6 {
public static void main(String args[]) { int n=1; long sum=0; while(true) { sum=sum+n; n++;
if(sum>=8888) break; }
System.out.println(\满足条件的最大整数:\ } }
习题四(第4章)
一、问答题
1. 封装、继承和多态。
2.当类名由几个单词复合而成时,每个单词的首字母使用大写。
3.名字的首单词的首字母使用小写,如果变量的名字由多个单词组成,从第2个单词开始的其它单词的首字母使用大写。 4.属性 5.行为
6.用类创建对象时。没有类型 7.用类创建对象时。
8.一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即或者是参数的个数不同,或者是参数的类型不同。可以。 9.可以。不可以。 10.不可以。
11.一个类通过使用new运算符可以创建多个不同的对象,不同的对象的实例变量将被分配不同的内存空间。所有对象的类变量都分配给相同的一处内存,对象共享类变量。 12.代表调用当前方法的对象。不可以。 二、选择题
1.B。2.D。3.D。4.D。5.CD。6.【代码1】【代码4】。7.【代码4】。 三、阅读程序
1.【代码1】:1,【代码2】:121,【代码3】:121。 2.sum=-100。 3. 27。 4.【代码1】:100,【代码2】:20.0。 5. 上机实习题目,解答略。 6. 上机实习题目,解答略。 四、编程题 CPU.java
public class CPU { int speed; int getSpeed() { return speed; }
public void setSpeed(int speed) { this.speed = speed; } }
HardDisk.java
public class HardDisk { int amount; int getAmount() {
return amount; }
public void setAmount(int amount) { this.amount = amount; } }
PC.java
public class PC { CPU cpu; HardDisk HD;
void setCPU(CPU cpu) { this.cpu = cpu; }
void setHardDisk(HardDisk HD) { this.HD = HD; }
void show(){
System.out.println(\速度:\ System.out.println(\硬盘容量:\ } }
Test.java
public class Test {
public static void main(String args[]) { CPU cpu = new CPU(); HardDisk HD=new HardDisk(); cpu.setSpeed(2200); HD.setAmount(200); PC pc =new PC(); pc.setCPU(cpu); pc.setHardDisk(HD); pc.show(); } }
习题五(第5章)
一、问答题 1.不可以。 2.是。 3.不继承。
4.声明与父类同名的成员变量。
5.子类重写的方法类型和父类的方法的类型一致或者是父类的方法的类型的子类型,重写的方法的名字、参数个数、参数的类型和父类的方法完全相同。重写方法的目的是隐藏继承的方法,子类通过方法的重写可以把父类的状态和行为改变为自身的状态和行为。 6.不可以。 7.Abstract类。
8.上转型对象不能操作子类新增的成员变量,不能调用子类新增的方法。上转型对象可以访问子类继承或隐藏的成员变量,可以调用子类继承的方法或子类重写的实例方法。 9.通过重写方法。
10.面向抽象编程目的是为了应对用户需求的变化,核心是让类中每种可能的变化对应地交给抽象类的一个子类类去负责,从而让该类的设计者不去关心具体实现。 二、选择题
1.C。2.D。3.CD。4.D。5.B。6.B。7.D。8.B。9.A。 三、阅读程序
1.【代码1】:15.0。【代码2】:8.0。 2.【代码1】:11。【代码2】:11。 3.【代码1】:98.0。【代码2】:12。【代码3】:98.0。【代码4】:9。 4.【代码1】:120。【代码2】:120。【代码3】:-100。 四、编程题 Animal.java
public abstract class Animal { public abstract void cry();
public abstract String getAnimalName(); }
Simulator.java
public class Simulator {
public void playSound(Animal animal) {
System.out.print(\现在播放\类的声音:\ animal.cry(); } }
Dog.java
public class Dog extends Animal { public void cry() {
System.out.println(\汪汪...汪汪\ }
public String getAnimalName() {
return \狗\ } }
Cat.java
public class Cat extends Animal { public void cry() {
System.out.println(\喵喵...喵喵\ }
public String getAnimalName() { return \猫\ } }
Application.java
public class Example5_13 {
public static void main(String args[]) { Simulator simulator = new Simulator(); simulator.playSound(new Dog()); simulator.playSound(new Cat()); } }
习题六(第6章)
一、问答题 1.不能。 2.不能。
3.可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中。那么该接口变量就可以调用被类实现的接口中的方法。 4.不可以。 5.可以。 二、选择题
1.D。2.AB。3.B。 三、阅读程序 1.【代码1】:15.0。【代码2】:8。 2.【代码1】:18。【代码2】:15。 四、编程题 Animal.java
public interface Animal { public abstract void cry();
public abstract String getAnimalName(); }
Simulator.java
public class Simulator {
public void playSound(Animal animal) {
System.out.print(\现在播放\类的声音:\ animal.cry(); } }
Dog.java
public class Dog implements Animal { public void cry() {
System.out.println(\汪汪...汪汪\ }
public String getAnimalName() { return \狗\ } }
Cat.java
public class Cat implements Animal { public void cry() {
System.out.println(\喵喵...喵喵\ }
public String getAnimalName() { return \猫\ } }
Application.java
public class Example5_13 {
public static void main(String args[]) { Simulator simulator = new Simulator(); simulator.playSound(new Dog()); simulator.playSound(new Cat()); } }
习题七(第7章)
一、问答题 1.有效。 2.可以。 3.不可以。 4.一定是。 二、选择题 1.C。2.C。 三、阅读程序
1.大家好,祝工作顺利! 2.p是接口变量。 3.你好 fine thanks。
4.属于上机实习程序,解答略。 四、编程题
import java.util.*; public class E {
public static void main (String args[ ]){ Scanner reader = new Scanner(System.in); double sum = 0; int m = 0;
while(reader.hasNextDouble()){ double x = reader.nextDouble(); assert x< 100:\数据不合理\ m = m+1; sum = sum+x; }
System.out.printf(\个数的和为%f\\n\ System.out.printf(\个数的平均值是%f\\n\ } }
习题八(第8章)
一、问答题
1.不是。\是。 2.4和3。
3.false和true。 4.负数。
5.是true。 6.3和-1。
7.会发生NumberFormatException异常。 二、选择题
1.A。2.C。3.B。4.D。5.C。 三、阅读程序 1.【代码】:苹果。 2.【代码】:Love:Game。 3.【代码1】:15。【代码2】:abc我们。 4.【代码】:13579。 5.【代码】:9javaHello。
6.属于上机实习程序,解答略。 7.属于上机实习程序,解答略。
四、编程题 1.public class E {
public static void main (String args[ ]) { String s1,s2,t1=\ s1=t1.toUpperCase(); s2=t1.toLowerCase(); System.out.println(s1); System.out.println(s2); String s3=s1.concat(s2); System.out.println(s3); } }
2. public class E {
public static void main (String args[ ]) { String s=\ char cStart=s.charAt(0);
char cEnd = s.charAt(s.length()-1); System.out.println(cStart); System.out.println(cEnd); } }
3. import java.util.*;
public class E {
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=2012; month1=0; day1=1; year2=2018; month2=0; day2=1; }
Calendar calendar=Calendar.getInstance(); calendar.set(year1,month1-1,day1); long timeYear1=calendar.getTimeInMillis(); calendar.set(year2,month2-1,day2); long timeYear2=calendar.getTimeInMillis();
long 相隔天数=Math.abs((timeYear1-timeYear2)/(1000*60*60*24)); System.out.println(\年\月\日和\
year2+\年\月\日相隔\相隔天数+\天\ } }
4. import java.util.*;
public class E {
public static void main (String args[ ]) { double a=0,b=0,c=0; a=12; b=24;
c=Math.asin(0.56); System.out.println(c); c=Math.cos(3.14); System.out.println(c); c=Math.exp(1); System.out.println(c); c=Math.log(8); System.out.println(c); } }
5.public class E {
public static void main (String args[ ]) { String str = \你是谁?\ String regex = \ str = str.replaceAll(regex,\
System.out.println(str); }
}
6. import java.util.*;
public class E {
public static void main(String args[]) {
String cost = \数学87分,物理76分,英语96分\ Scanner scanner = new Scanner(cost); scanner.useDelimiter(\ double sum=0; int count =0;
while(scanner.hasNext()){
try{ double score = scanner.nextDouble(); count++; sum = sum+score; System.out.println(score); }
catch(InputMismatchException exp){ String t = scanner.next(); } }
System.out.println(\总分:\分\ System.out.println(\平均分:\分\ } }
习题九(第9章)
一、问答题
1.Frame容器的默认布局是BorderLayout布局。 2.不可以。
3.ActionEvent。 4.DocumentEvent。 5.5个。
6.MouseMotionListener。 二、选择题
1.C。2.A。3.A。4.D。5.C。 三、编程题
1. import java.awt.*;
import javax.swing.event.*; import javax.swing.*;
import java.awt.event.*; 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(JFrame.DISPOSE_ON_CLOSE); }
public void changedUpdate(DocumentEvent e) { String s=text1.getText();
String []a =s.split(\ sum=0; aver=0;
for(int i=0;i
try { sum=sum+Double.parseDouble(a[i]); }
catch(Exception ee) {} }
aver=sum/count; text2.setText(null); text2.append(\和:\ text2.append(\平均值:\ }
public void removeUpdate(DocumentEvent e){ changedUpdate(e); }
public void insertUpdate(DocumentEvent e){ changedUpdate(e);
} }
2. import java.awt.*;
import javax.swing.event.*; import javax.swing.*; import java.awt.event.*; 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(\ 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);
buttonAdd.addActionListener(this); buttonSub.addActionListener(this); buttonMul.addActionListener(this); buttonDiv.addActionListener(this); setSize(300,320); setVisible(true); validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); }
public void actionPerformed(ActionEvent e) { double n;
if(e.getSource()==buttonAdd) { 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()==buttonSub) { 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()==buttonMul) {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()==buttonDiv) {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(); } }
3. import java.awt.*;
import java.awt.event.*; import javax.swing.*; public class E {
public static void main(String args[]){ Window win = new Window(); win.setTitle(\使用MVC结构\ win.setBounds(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(JFrame.EXIT_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(); pNorth.add(new JLabel(\上底:\ pNorth.add(textAbove);
pNorth.add(new JLabel(\下底:\ pNorth.add(textBottom); pNorth.add(new JLabel(\高:\
pNorth.add(textHeight); pNorth.add(controlButton);
controlButton.addActionListener(this); add(pNorth,BorderLayout.NORTH);
add(new JScrollPane(showArea),BorderLayout.CENTER); }
public void actionPerformed(ActionEvent e) { try{
double above = Double.parseDouble(textAbove.getText().trim()); double bottom = Double.parseDouble(textBottom.getText().trim()); double height = Double.parseDouble(textHeight.getText().trim()); lader.setAbove(above) ; lader.setBottom(bottom); lader.setHeight(height);
double area = lader.getArea(); showArea.append(\面积:\ }
catch(Exception ex) {
showArea.append(\ } } }
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; } }
习题十(第10章)
一、问答题
1.使用FileInputStream。
2.FileInputStream按字节读取文件,FileReader按字符读取文件。 3.不可以。
4.使用对象流写入或读入对象时,要保证对象是序列化的。
5.使用对象流很容易得获取一个序列化对象的克隆,只需将该对象写入到对象输出流,那么用对象输入流读回的对象一定是原对象的一个克隆。 二、选择题 1.C。2.B。 三、阅读程序 1.【代码1】:51。【代码2】:0。 2.【代码1】:3。【代码2】:abc。【代码3】:1。【代码4】:dbc。 3.上机实习题,解答略。 四、编程题
1. import java.io.*;
public class E {
public static void main(String args[]) { File f=new File(\
try{ RandomAccessFile random=new RandomAccessFile(f,\ 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; random.seek(m); byte cc[]=new byte[2]; random.readFully(cc);
System.out.print(new String(cc)); } } }
catch(Exception exp){} } }
2. import java.io.*;
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++;
out.write(i+\ out.newLine(); s=inTwo.readLine(); }
inOne.close(); inTwo.close(); out.flush(); out.close(); tofile.close(); }
catch(IOException e){} } }
3. import java.io.*;
import java.util.*; public class E {
public static void main(String args[]) { File file = new File(\ Scanner sc = null; double sum=0; int count = 0;
try { sc = new Scanner(file);
sc.useDelimiter(\ while(sc.hasNext()){
try{ double price = sc.nextDouble(); count++; sum = sum+price; System.out.println(price); }
catch(InputMismatchException exp){ String t = sc.next(); } }
{ public void paint(Graphics g)
{ Graphics2D g_2d=(Graphics2D)g; Ellipse2D ellipse1=
new Ellipse2D. Double (20,80,60,60), ellipse2=
new Ellipse2D. Double (40,80,80,80); g_2d.setColor(Color.white); Area a1=new Area(ellipse1), a2=new Area(ellipse2); a1.subtract(a2); //\差\ g_2d.fill(a1); } }
public class E {
public static void main(String args[]) { JFrame f=new JFrame(); f.setSize(500,450); f.setVisible(true); Moon moon=new Moon(); moon.setBackground(Color.black); f.add(moon,\ f.validate();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } }
习题十五(第15章)
一、问答题
1.LinkedList使用链式存储结构,ArrayList使用顺序存储结构。
2.迭代器遍历在找到集合中的一个对象的同时,也得到待遍历的后继对象的引用,因此迭代器可以快速地遍历集合。 3.不是。
4.用HashMap
2.ABCD。 三、编写程序 1. import java.util.*;
public class E {
public static void main(String args[]) {
Stack
Integer temp=new Integer(2*f1+2*f2); System.out.println(\ stack.push(temp); stack.push(F2); k++; } } } }
2. import java.util.*;
class Student implements Comparable { int english=0; String name;
Student(int english,String name) { this.name=name; this.english=english; }
public int compareTo(Object b) { Student st=(Student)b; return (this.english-st.english); } }
public class E {
public static void main(String args[]) {
List
String name[]={\张三\李四\旺季\加戈\为哈\周和\赵李\将集\ for(int i=0;i list.add(new Student(score[i],name[i])); } Iterator TreeSet Iterator System.out.println(\ } } } 3. import java.util.*; class UDiscKey implements Comparable { double key=0; UDiscKey(double d) { key=d; } public int compareTo(Object b) { UDiscKey disc=(UDiscKey)b; if((this.key-disc.key)==0) return -1; else return (int)((this.key-disc.key)*1000); } } class UDisc{ int amount; double price; UDisc(int m,double e) { amount=m; price=e; } } public class E { public static void main(String args[ ]) { TreeMap int amount[]={1,2,4,8,16}; double price[]={867,266,390,556}; UDisc UDisc[]=new UDisc[4]; for(int k=0;k UDisc[k]=new UDisc(amount[k],price[k]); } UDiscKey key[]=new UDiscKey[4] ; for(int k=0;k key[k]=new UDiscKey(UDisc[k].amount); } for(int k=0;k treemap.put(key[k],UDisc[k]); } int number=treemap.size(); Collection System.out.println(\元\ } treemap.clear(); for(int k=0;k key[k]=new UDiscKey(UDisc[k].price); } for(int k=0;k number=treemap.size(); collection=treemap.values(); iter=collection.iterator(); while(iter.hasNext()) { UDisc disc=iter.next(); System.out.println(\元\ } } } 习题十六(第16章) 1. import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Xiti2 extends Applet implements ActionListener { TextField text1,text2; Label label; public void init() { text1=new TextField(10); text2=new TextField(20); Box box1=Box.createHorizontalBox(); Box box2=Box.createHorizontalBox(); Box boxV=Box.createVerticalBox(); box1.add(new Label(\输入一个数回车确定:\ box1.add(text1); label=new Label(\数的平方:\ box2.add(label); box2.add(text2); boxV.add(box1); boxV.add(box2); add(boxV); text2.setEditable(false); text1.addActionListener(this); } public void actionPerformed(ActionEvent e) { String number=e.getActionCommand(); try{ double n=Double.parseDouble(number); double m=n*n; label.setText(n+\的平方:\ text2.setText(\ text1.setText(\ validate(); } catch(NumberFormatException exp) { text2.setText(\ } } } 2. import java.applet.*; import java.awt.*; 8.属于上机调试题目,解答略 四、编写程序 1. public class E { public static void main(String args[]) { Cinema a=new Cinema(); a.zhang.start(); a.sun.start(); a.zhao.start(); } } class TicketSeller //负责卖票的类。 { int fiveNumber=3,tenNumber=0,twentyNumber=0; public synchronized void sellTicket(int receiveMoney) { if(receiveMoney==5) { fiveNumber=fiveNumber+1; System.out.println(Thread.currentThread().getName()+ \给我5元钱,这是您的1张入场卷\ } else if(receiveMoney==10) { while(fiveNumber<1) { try { System.out.println(Thread.currentThread().getName()+\靠边等\ wait(); System.out.println(Thread.currentThread().getName()+\结束等待\ } catch(InterruptedException e) {} } fiveNumber=fiveNumber-1; tenNumber=tenNumber+1; System.out.println(Thread.currentThread().getName()+ \给我10元钱,找您5元,这是您的1张入场卷\ } else if(receiveMoney==20) { while(fiveNumber<1||tenNumber<1) { try { System.out.println(Thread.currentThread().getName()+\靠边等\ wait(); System.out.println(Thread.currentThread().getName()+\结束等待\ } catch(InterruptedException e) {} } fiveNumber=fiveNumber-1; tenNumber=tenNumber-1; twentyNumber=twentyNumber+1; System.out.println(Thread.currentThread().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(\张小有\ sun.setName(\孙大名\ zhao.setName(\赵中堂\ seller=new TicketSeller(); } public void run() { if(Thread.currentThread()==zhang) { seller.sellTicket(20); } else if(Thread.currentThread()==sun) { seller.sellTicket(10); } else if(Thread.currentThread()==zhao) { seller.sellTicket(5); } } } 2. 参照本章例子6 3.参照本章例子9 习题十三(第13章) 一、问答题 1.一个URL对象通常包含最基本的三部分信息:协议、地址、资源。 2.URL对象调用InputStream openStream() 方法可以返回一个输入流,该输入流指向URL对象所包含的资源。通过该输入流可以将服务器上的资源信息读入到客户端。 3.客户端的套接字和服务器端的套接字通过输入、输出流互相连接后进行通信。 4.使用方法accept(),accept()会返回一个和客户端Socket对象相连接的Socket对象。accept方法会堵塞线程的继续执行,直到接收到客户的呼叫。。 5.域名/IP。 四、编程题 1. (1)客户端 import java.net.*; import java.io.*; import java.awt.*; import java.awt.event.*; 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=Box.createVerticalBox(); connection=new Button(\连接服务器\ send=new Button(\发送\ send.setEnabled(false); inputText=new TextField(12); showResult=new TextField(12); box.add(connection); box.add(new Label(\输入三角形三边的长度,用逗号或空格分隔:\ box.add(inputText); box.add(send); box.add(new Label(\收到的结果:\ box.add(showResult); connection.addActionListener(this); send.addActionListener(this); thread=new Thread(this); add(box); setBounds(10,30,300,400); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void actionPerformed(ActionEvent e) { if(e.getSource()==connection) { try //请求和服务器建立套接字连接: { if(socket.isConnected()) {} else { InetAddress address=InetAddress.getByName(\ InetSocketAddress socketAddress=new InetSocketAddress(address,4331); socket.connect(socketAddress); in =new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); send.setEnabled(true); thread.start(); } } catch (IOException ee){} } if(e.getSource()==send) { String s=inputText.getText(); if(s!=null) { try { out.writeUTF(s); } catch(IOException e1){} } } } public void run() { String s=null; while(true) { try{ s=in.readUTF(); showResult.setText(s); } catch(IOException e) { showResult.setText(\与服务器已断开\ break; } } } } (2)服务器端 import java.io.*; import java.net.*; import java.util.*; 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) { System.out.println(\正在监听\对象不能重复创建 } try{ System.out.println(\等待客户呼叫\ you=server.accept(); System.out.println(\客户的地址:\ } catch (IOException e) { System.out.println(\正在等待客户\ } if(you!=null) { new Server_thread(you).start(); //为每个客户启动一个专门的线程 } } } } class Server_thread extends Thread
正在阅读:
java2实用教程第4版 - 习题解答11-12
数据、模型和决策案例05-05
思想道德修养与法律基础期末考试试卷(A)05-24
话题作文二例04-15
健美操判断题 完全版09-04
质量管理试题及答案03-26
- exercise2
- 铅锌矿详查地质设计 - 图文
- 厨余垃圾、餐厨垃圾堆肥系统设计方案
- 陈明珠开题报告
- 化工原理精选例题
- 政府形象宣传册营销案例
- 小学一至三年级语文阅读专项练习题
- 2014.民诉 期末考试 复习题
- 巅峰智业 - 做好顶层设计对建设城市的重要意义
- (三起)冀教版三年级英语上册Unit4 Lesson24练习题及答案
- 2017年实心轮胎现状及发展趋势分析(目录)
- 基于GIS的农用地定级技术研究定稿
- 2017-2022年中国医疗保健市场调查与市场前景预测报告(目录) - 图文
- 作业
- OFDM技术仿真(MATLAB代码) - 图文
- Android工程师笔试题及答案
- 生命密码联合密码
- 空间地上权若干法律问题探究
- 江苏学业水平测试《机械基础》模拟试题
- 选课走班实施方案
- 习题
- 解答
- 实用
- 教程
- java2
- 《仪器分析》朱明华 - 第三版 - 课后习题解答
- 用心去工作 - 成就事业的前提
- 消费者行为学考点提纲
- 天津经济技术开发区一办法三手册
- 大学《传播学概论》试卷和答案
- 采购的主要方法
- 中国法下承运人货损赔偿责任限额
- 余庆县松烟中学2012-2015实施方案
- 人民币汇率改革习题与答案
- 相-桥梁动静载回弹法检测混凝土强度检测重点难点分析
- 无机合成化学简明教程课后习题参考答案
- 大体积混凝土专项施工方案
- 中西文化差异导致的翻译错误
- corejava学习总结
- 人教版五年级数学上册全册教案 - 图文
- 《药物治疗学》复习题二
- 2016-2017六年级英语下学期期末试卷
- 洗衣机日抽样检验(OQC)操作规程 -
- 圆周率前200位故事
- 新版《电力设备典型消防规程》.doc