import java.applet.*; import java.awt.*;
public class FirstApplet extends Applet {
public void paint(Graphics g) {
【代码:g.setColor(Color.blue);】//将当前字体颜色设置为蓝色 g.drawString(\"这是一个Java Applet 程序\//在Java Applet中绘制一行文字:“这是一个Java Applet 程序” 【代码:g.setColor(Color.red);】 //将当前字体颜色设置为红色 g.setFont(new Font(\"宋体\
【代码:g.drawString(“我改变了字体”,10,100);】//在Java Applet中坐标(10,100)处绘制一行文字:“我改变了字体” } }
(1) 将源文件保持为FirstApplet.java,编译源文件。编译命令:【代码javac FirstApplet】 (2) 编写一个html文件FirstApplet.html,将该文件和源程序保持在同一目录下。文件内容如
下:
(3) 若用appletviewer打开FirstApplet.html文件。
运行命令为:【代码appletviewer FirstApplet】
2. 要求:从键盘输入任意两个实数,比较两个数字的大小,将较大的数输出。数据输入和输出用Java的标准输入流和输出流来实现。阅读分析下面程序,将程序中的代码补充完整,实现数据比较功能。
import java.util.Scanner; publicclass CompareTwoNumbers { doublenumber1,number2; Scanner scanner;
public CompareTwoNumbers(){
System.out.println(\"请输入两个数字:\");
scanner=new Scanner(代码1:system.in);//实例化一个Scanner对象;
number1=代码2 :scanner.nextDouble();//从键盘输入一个实数赋值给number1; number2=代码3 :scanner.nextDouble();;// 从键盘输入一个实数赋值给number2; System.out.println(\"较大的数值是:\"+代码4 :Math.max(number1,number2)); //将number1和number2中的较大值输出; }
publicstaticvoid main(String args[]){
CompareTwoNumbers ct=new CompareTwoNumbers (); System.exit(0); } }
3.猜数字游戏
阅读分析下面程序,将程序中的代码补充完整,编辑运行查看结果。 //GuessNumber.java
import javax.swing.JOptionPane; public class GuessNumber {
public static void main (String args[ ]) {
System.out.println(\"给你一个1至100之间的整数,请猜测这个数\"); int realNumber=(int)(Math.random()*100)+1; int yourGuess=0;
String str=JOptionPane.showInputDialog(\"输入您的猜测:\"); yourGuess=Integer.parseInt(str);
while(【代码1 : yourGuess != realNumber】) //循环条件 {
if(【代码2 : yourGuess > realNumber】) //条件代码 {
str=JOptionPane.showInputDialog(\"猜大了,再输入你的猜测:\"); yourGuess=Integer.parseInt(str); }
else if(【代码3 : yourGuess < realNumber】) //条件代码 {
str=JOptionPane.showInputDialog(\"猜小了,再输入你的猜测:\"); yourGuess=Integer.parseInt(str); } }
System.out.println(\"猜对了!\"); } }
4.String类的常用方法。
阅读分析下面程序,把程序中的代码补充完整,并查看结果。
//StringExample.java
class StringExample
{ public static void main(String args[])
{ String s1=new String(\"you are a student\"), s2=new String(\"how are you\");
if(【代码1 :s1.equals(s2)】) // 使用equals方法判断s1与s2是否相同 {
System.out.println(\"s1与s2相同\");
} else {
System.out.println(\"s1与s2不相同\"); }
String s3=new String(\"22030219851022024\");
if(【代码2 :s3.startWith(“220302”)】) //判断s3的前缀是否是“220302”。 {
System.out.println(\"吉林省的身份证\"); }
String s4=new String(\"你\"), s5=new String(\"我\");
if(【代码3 :s4.compareTo(s5) > 0】)//按着字典序s4大于s5的表达式。 {
System.out.println(\"按字典序s4大于s5\"); } else {
System.out.println(\"按字典序s4小于s5\"); }
int position=0;
String path=\"c:\\\\java\\\\jsp\\\\A.java\";
String fileName=【代码4 :path.concat(“A.java”);】//获取path中“A.java”子字符串。
System.out.println(\"c:\\\\java\\\\jsp\\\\A.java中含有的文件名:\"+fileName);
String s6=new String(\"100\"), s7=new String(\"123.678\");
int n1=【代码5 :Integer.parseInt(s6);】 //将s6转化成int型数据。 double n2=【代码6 :Double.parseDouble(s7);】 //将s7转化成double型数据。
double m=n1+n2;
System.out.println(m);
String s8=【代码7 :String.valueOf(m);】 //String调用valuOf(int n)方法将m转化为字符串对象
position=s8.indexOf(\".\");
String temp=s8.substring(position+1);
System.out.println(\"数字\"+m+\"有\"+temp.length()+\"位小数\") ; String s9=new String(\"ABCDEF\");
char a[]=【代码8 :s9.toCharArray();】 //将s9存放到数组a中。 for(int i=a.length-1;i>=0;i--) {
System.out.print(\" \"+a[i]); }
} }
5.掌握嵌套类和内部类的概念和用法
编写一个程序要求定义一个外部类Outer,然后在Outer类中定义一个内部类Inner和局部类Local,内部类Inner和局部类Local的任务都是显示出外部类中的数组元素,然后求出这些数组元素的平均值。
请按模版要求,将代码补充完整。 class Outer {
privateintdata[]; Outer(int x[]) { data = x; }
void checkInner() {
Inner innerObj = new Inner(); 【补充代码 : innerObj.show();】// 调用Inner对象的show()方法
System.out.println(\"内部类计算的平均值: \" + innerObj.average()); }
void checkLocal() { class Local { void show() {
System.out.print(\"从局部类显示数组元素:\"); for (int i = 0; i int average() { int sum = 0; for (int i = 1; i Local localObj = new Local(); localObj.show(); System.out.println(\"局部类计算的平均值: \" + localObj.average()); } class Inner { void show() { System.out.print(\"从内部类显示数组元素:\"); for (int i = 0; i System.out.println(); } int average() { int sum = 0; for (int i = 1; i publicclass InnerClassTest { publicstaticvoid main(String[] args) { int a[] = { 6, 8, 9, 22, 34, 7, 2, 1, 15 }; Outer outerObj = new Outer(a); outerObj.checkInner(); 【补充代码outerObj.checkLocal();】// 调用outerObj对象的checkLocal方法 } } 6.通过一个简单的例子理解多态的概念 /** * 人民 */ publicinterface IPolice { /** * 抓小偷 */ publicvoid catchThief(); } /** * 一个,执行抓小偷任务. */ publicclass PoliceReal implements IPolice { publicvoid catchThief() { System.out.println(\"抓住小偷了\"); } } /** * 另一个,也执行抓小偷任务. */ publicclass PoliceHyp implements IPolice { publicvoid catchThief() { System.out.println(\"大冷天的抓什么小偷啊,不如偷个菜.\"); } } /** * 市民 */ publicclass Citizen { private String mName; public Citizen(String name) { mName = name; } /** * 市民报案 */ publicvoid report(IPolice police) { System.out.println(String.format(\"市民%s丢失手机,向报案抓小偷.\", mName)); police.catchThief(); } } 案情: 市民虽然向报了案, 但你不知道能不能把小偷抓住, 甚至你都不知道他们有没有去抓小偷, 还有可能你在电影里看到的剧情真的发生了... 事情经过可能是这样: publicclassMain { publicstaticvoid main(String[] args) { Citizen citizen = new Citizen(\"张三\"); IPolice police = getPolice(); citizen.report(police); } privatestatic IPolice getPolice() { returnnew PoliceReal(); } } 事情结果一: 市民张三丢失手机,向报案抓小偷. 抓住小偷了 事情经过也可能是这样: publicclassMain { publicstaticvoid main(String[] args) { Citizen citizen = new Citizen(\"张三\"); IPolice police = getPolice(); citizen.report(police); } privatestatic IPolice getPolice() { returnnew PoliceHyp(); } } 事情结果二: 市民张三丢失手机,向报案抓小偷. 大冷天的抓什么小偷啊,不如偷个菜. 事情经过还可能是这样: publicclassMain { publicstaticvoid main(String[] args) { Citizen citizen = new Citizen(\"张三\"); IPolice police = getPolice(); citizen.report(police); } privatestatic IPolice getPolice() { returnnew PoliceReal() { @Override publicvoid catchThief() { System.out.println(\"抓小偷?笑话,抓了小偷我哪儿收保护费去啊.\"); } }; } } 事情结果三: 市民张三丢失手机,向报案抓小偷. 抓小偷?笑话,抓了小偷我哪儿收保护费去啊. 7.阅读并分析以下程序,将程序中的代码补充完整。 public class CalendarFrame extends Frame implements ActionListener { Label labelDay[]=new Label[42]; Button titleName[]=new Button[7]; String name[]={\"日\一\二\三\四\五\六\ Button nextMonth,previousMonth; int year=2006,month=10; CalendarBean calendar; Label showMessage=new Label(\"\ public CalendarFrame() { Panel pCenter=new Panel(); 【代码1 :pCenter.setLayout(new GridLayout(7,7));】 //将pCenter的布局设置为7行7列的GridLayout 布局。 for(int i=0;i<7;i++) { titleName[i]=new Button(name[i]); 【代码2 : pCenter.add(titleName[i]);】//pCenter添加组件titleName[i]。 } for(int i=0;i<42;i++) { labelDay[i]=new Label(\"\ 【代码3 : pCenter.add(labelDay[i]);】//pCenter添加组件labelDay[i]。 } calendar=new CalendarBean(); calendar.setYear(year); calendar.setMonth(month); String day[]=calendar.getCalendar(); for(int i=0;i<42;i++) { labelDay[i].setText(day[i]); } nextMonth=new Button(\"下月\"); previousMonth=new Button(\"上月\"); nextMonth.addActionListener(this); previousMonth.addActionListener(this); Panel pNorth=new Panel(), pSouth=new Panel(); pNorth.add(previousMonth); pNorth.add(nextMonth); pSouth.add(showMessage); showMessage.setText(\"日历:\"+calendar.getYear()+\"年\"+ calendar.getMonth()+\"月\" ); ScrollPane scrollPane=new ScrollPane(); scrollPane.add(pCenter); 【代码4 :add(“Center”,scollPane);】// 窗口添加scrollPane在中心区域 【代码5 :add(“North”,pNorth);】// 窗口添加pNorth 在北面区域 【代码6 :add(“South”,pSouth);】// 窗口添加pSouth 在南区域。 } public void actionPerformed(ActionEvent e) { if(e.getSource()==nextMonth) { month=month+1; if(month>12) month=1; calendar.setMonth(month); String day[]=calendar.getCalendar(); for(int i=0;i<42;i++) { labelDay[i].setText(day[i]); } } else if(e.getSource()==previousMonth) { month=month-1; if(month<1) month=12; calendar.setMonth(month); String day[]=calendar.getCalendar(); for(int i=0;i<42;i++) { labelDay[i].setText(day[i]); } } showMessage.setText(\"日历:\"+calendar.getYear()+\"年\"+calendar.getMonth()+\"月\" ); } } 8.使用滚动条改变背景颜色 程序功能:移动滚动条可以改变背景颜色。阅读并分析以下程序,将程序中的代码补充完整。 publicclass KY7_2 extends Applet implements AdjustmentListener { Scrollbar r1, r2, r3; intred, green, blue; TextField t; Label a; publicvoid init() { setLayout(null); r1 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 255); r2 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 255); r3 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 255); t = new TextField(\"0\", 5); t.setEditable(false); a = new Label(\"移动滚动条可改变背景颜色\", Label.CENTER); add(a); a.setBounds(120, 10, 150, 15); 代码1 :add(r1);//添加滚动条r1 r1.setBounds(20, 30, 100, 20); 代码2 :add(r2);//添加滚动条r2 r2.setBounds(140, 30, 100, 20); 代码3 :add(r3);//添加滚动条r3 r3.setBounds(260, 30, 100, 20); add(t); t.setBounds(20, 120, 220, 18); r1.addAdjustmentListener(this); 代码4 :r2.addAdjustmentListener(this); 代码5 :r3.addAdjustmentListener(this); } publicvoid adjustmentValueChanged(AdjustmentEvent e) { red = r1.getValue(); 代码6 :green = r2.getValue(); 代码7 :blue =r3.getValue(); t.setText(\"red 的值\" + String.valueOf(r1.getValue()) + \的 值\" + String.valueOf(r2.getValue()) + \的值\" + String.valueOf(r3.getValue())); } Color c = new Color(red, green, blue); 代码8 :setBackground(c);//设置背景色 } 9.创建电闪雷鸣的动画 程序功能:本程序可以通过按钮控制声音和动画的开始和停止操作。动画显示了电闪雷鸣的场面。注意:图像文件要分别表现不同时间段的电闪场面,这样才会有动画效果。 阅读并分析以下程序,将程序中的代码补充完整。 import java.awt.*; import java.applet.*; import java.awt.event.*; publicclass KY7_3extends Applet implements Runnable, ActionListener { Image iImages[]; // 图像数组 Thread aThread; intiFrame; // 图像数组下标 AudioClip au; // 定义一个声音对象 Button b1, b2; publicvoid init() { int i, j; iFrame = 0; aThread = null; } iImages = new Image[10]; for (i = 0; i < 10; i++) { } au = getAudioClip(getDocumentBase(), \"Wav/receivemedia.au\"); 代码1 :au.play();// 播放一次声音文件 Panel p1 = new Panel(); b1 = new Button(\"开始\"); b2 = new Button(\"停止\"); p1.add(b1); p1.add(b2); b1.addActionListener(this); b2.addActionListener(this); setLayout(new BorderLayout()); add(p1, \"South\"); iImages[i] = getImage(getCodeBase(), \"images/\" + \"tu\" + (i + 1)+ \".JPG\"); publicvoid start() { } publicvoid stop() { } publicvoid run() { } publicvoid update(Graphics g) { while (true) { } iFrame++; iFrame %= (iImages.length); // 下一幅图像的下标 repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { // 中断时抛出 break; // 退出循环 } if (aThread != null) { } 代码3 :aThread.interrupt();// 线程中断 aThread = null; 代码4 :au.stop();// 停止播放声音文件 if (aThread == null) { } aThread = new Thread(this); 代码2 :aThread.star();// 线程启动 b1.setEnabled(false); } g.drawImage(iImages[iFrame], 0, 0, this); publicvoid actionPerformed(ActionEvent e) { if ((e.getSource() == b1) && (aThread == null)) { // 单击 Start 按 aThread = new Thread(this); 代码5 :aThread.star();// 线程启动 b1.setEnabled(false); b2.setEnabled(true); 钮时触发 } } 代码6 :au.loop();// 循环播放声音文件 } if (代码7 :au.stop();) { // 单击 Stop 按钮时触发 aThread.interrupt(); // 线程中断 aThread = null; b1.setEnabled(true); b2.setEnabled(false); au.stop(); // 停止播放声音文件 } 10.要求设计一个能通过Runnable接口实现多线程动态地显示时间的Applet程序。 阅读并分析以下程序,将程序中的代码补充完整,编译并运行程序,查看结果。 import javax.swing.*; // Japplet import java.util.*; // Calendar import java.awt.*; // Graphics publicclass AppletThreaded extends JApplet 代码1 :implementsRunnable { Thread appletThread; inthours, mins, secs; Boolean stopFlag; // applet的start( )方法 publicvoid start() { appletThread = new Thread(this); 代码2 :appletThread.star();;//启动线程 stopFlag=false; } // 线程的run( )方法 publicvoid run() { while (true) { try { 代码3 :Thread.sleep(1000);让线程休眠时间为1000 } catch(InterruptedException exception){ exception.printStackTrace(); } //产生一个代表当前时间的Calendar子类的实例 Calendar time = Calendar.getInstance(); hours = time.get(Calendar.HOUR); mins = time.get(Calendar.MINUTE); secs = time.get(Calendar.SECOND); System.out.println(\"秒 : \" + secs); 代码4 :repaint();;//刷新显示时间 if(stopFlag) break; } } publicvoid stop() { stopFlag=true; } publicvoid paint(Graphics g) { super.paint(g); g.drawString(String.valueOf(hours) + \":\" + String.valueOf(mins) + \":\" + String.valueOf(secs), 50 , 50); } } 11.编写一个应用程序,除了主线程外,还有两个线程:first和second。first负责模拟一个红色的按钮从坐标(10,60)运动到(100,60);second负责模拟一个绿色的按钮从坐标(100,60)运动到(200,60)。阅读并分析以下程序, 将程序中的代码补充完整。 //MoveButton.java import java.awt.*; import java.awt.event.*; public class MoveButton extends Frame implements Runnable,ActionListener { 【代码1:Thread first,second;】//用Thread类声明first,second两个线程对象 Button redButton,greenButton,startButton; int distance=10; MoveButton() { 【代码2 :first = new Thread ();】 //创建first线程,当前窗口做为该线程的目标对象 【代码3 :second = new Thread ();】 //创建second线程,当前窗口做为该线程的目标对象 redButton=new Button(); greenButton=new Button(); redButton.setBackground(Color.red); greenButton.setBackground(Color.green); startButton=new Button(\"start\"); startButton.addActionListener(this); setLayout(null); add(redButton); redButton.setBounds(10,60,15,15); add(greenButton); greenButton.setBounds(100,60,15,15); add(startButton); startButton.setBounds(10,100,30,30); setBounds(0,0,300,200); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { try{ first.start(); second.start(); } catch(Exception exp){} } public void run() { while(true) { if(【代码4 :Thead.currentThread() == first】) //判断当前占有CPU资源的线程是否是first { moveComponent(redButton); try{ Thread.sleep(20); } catch(Exception exp){} } if(【代码5 :Thread.currentThread() == second】) //判断当前占有CPU资源的线程是否是second { moveComponent(greenButton); try{ Thread.sleep(10); } catch(Exception exp){} } } } public synchronized void moveComponent(Component b) { if(Thread.currentThread()==first) { while(distance>100&&distance<=200) try{ wait(); } catch(Exception exp){} distance=distance+1; b.setLocation(distance,60); if(distance>=100) { b.setLocation(10,60); notifyAll(); } } if(Thread.currentThread()==second) { while(distance>=10&&distance<100) try{ wait(); } catch(Exception exp){} distance=distance+1; b.setLocation(distance,60); if(distance>200) { distance=10; b.setLocation(100,60); notifyAll(); } } } } // MoveButtonMainClass.java MoveButtonMainClass.java public class MoveButtonMainClass { public static void main(String args[]) { MoveButton mb =new MoveButton(); } } 12.读写基本数据类型数据 编写一个Java应用程序,将若干基本数据写入到一个文件,然后在按顺序读出。阅读下面程序,将程序中的代码补充完整。 import java.io.*; public class NumberExample{ public static void main(String args[]){ int a1=12, a2=1180; long b=808080; float x1=3.14F,x2=12.456F; double d=1234.9876; Boolean boo1=true,boo2=false; char c=’我’; File f=【代码1 :new File(“E://1.txt”);】//创建文件 try{FileOutputStream fos=【代码2 :new FileOutputStream(f);】//创建指向f文件输出流 DataOutputStream out_data=【代码3 :new DataOutputStream(fos);】//创建指向fos的数据输出流 【代码4 : out_data.writeInt(a1);】//out_data将数据a1写入到文件 【代码5 : out_data.writeInt(a2);】//out_data将数据a2写入到文件 【代码6 : out_data.writeLong(b);】//out_data将数据b写入到文件 【代码7 :out_data.writeFloat(x1);】//out_data将数据x1写入到文 件 【代码8 :out_data.writeFloat(x2);】//out_data将数据x2写入到文 件 【代码9 :out_data.writeDouble(d);】//out_data将数据d写入到文件 【代码10 :out_data.writeBoolean(boo1);】//out_data将数据boo1 写入到文件 【代码11 :out_data.writeBoolean(boo2);】//out_data将数据boo2 写入到文件 【代码12 :out_data.writeChar(c);】//out_data将数据c写入到文件 } Catch(IOException e) { } try {FileInputStream fis=【代码13 :new FileInputStream(f);】//创建指向f文件输入流 DataInputStream in_data=【代码14 :new DataInputStream(fis);】//创建指向fis的数据输入流 System.out.println(【代码15 : in_data.readInt()】); //in_data读取int整数 System.out.println(【代码16 : in_data.readInt()】); //in_data读取int整数 System.out.println(【代码17 :in_data.readLong()】); //in_data读取long整数 System.out.println(【代码18:in_data.readFloat()】); //in_data读取float数 System.out.println(【代码19 :in_data.readFloat()】); //in_data读取float数 System.out.println(【代码20 : in_data.readDouble()】); //in_data读取double数 System.out.println(【代码21 :in_data.readBoolean()】); //in_data读取boolean数 System.out.println(【代码22 : in_data.readBoolen()】); //in_data读取boolean数 System.out.println(【代码23 :in_data.readChar()】); //in_data读取char数据 } Catch(IOException e){ } } } } 13.练习使用InetAddress类。对程序进行分析,写出分析结果。 import java.net.*; publicclass GetIP { publicstaticvoid main(String args[]) { try { } InetAddress address_1 = InetAddress.getLocalHost(); // 获得本地主机的计算机名和IP地址 System.out.println(address_1.toString()); InetAddress address_2 = InetAddress.getByName(\"res.qcxy.hb.cn\"); // 获得主机地址的域名和IP地址 System.out.println(address_2.toString()); InetAddress address_3 = InetAddress.getByName(\"61.183.20.30\"); System.out.println(address_3.toString()); } } catch (UnknownHostException e) { System.out.println(\"无法找到………….\"); } 14.阅读下面的程序并补充完整,掌握获取URL信息的一些方法。 import java.net.*; import java.io.*; publicclass URLTest { publicstaticvoid main(String[] args) { URL url = null; InputStream is; try { url = new URL(\"http://res.qcxy.hb.cn:8080/eas/index.html\"); is = url.openStream(); int c; try { while ((c = is.read()) != -1) System.out.print((char) c); } catch (IOException e) { } finally { is.close(); } } e.printStackTrace(); e.printStackTrace(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println(\"文件名:\" + 【代码1 :url.getFile()】); //获取url对象的文件名 System.out.println(\"主机名:\" + 【代码2 :url.getHost()】);//获取主机名 System.out.println(\"端口号:\" + 【代码3 :url.getPort()】);//获取端口号 System.out.println(\"协议名:\" + 【代码4 :url.getProtcol()】);//获取 协议名称 } } 15.练习使用Socket和ServerSocket进行套接字编程 下面是一个简单的字符界面的聊天程序。 服务器端程序如下: import java.io.*; import java.net.*; public class ServerDemo { public static void main(String args[]){ try{ ServerSocket server=new ServerSocket(4566); Socket socket=server.accept(); String line; BufferedReader is=new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintWriter os=new PrintWriter(socket.getOutputStream()); BufferedReader sin=new BufferedReader( System.out.println(\"Client:\"+is.readLine()); System.out.print(\"Server:\"); line=sin.readLine(); while(!line.equals(\"bye\")){ os.println(line); os.flush(); System.out.println(\"Client:\"+is.readLine()); System.out.print(\"Server:\"); line=sin.readLine(); new InputStreamReader(System.in)); } } } } sin.close(); os.close(); is.close(); socket.close(); server.close(); System.out.println(\"Error:\"+e); }catch(Exception e){ 客户端程序如下: import java.io.*; import java.net.*; publicclass ClientDemo { } publicstaticvoid main(String args[]){ } try{ } Socket socket=new Socket(\"127.0.0.1\",4566); BufferedReader is=new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintWriter os=new PrintWriter(socket.getOutputStream()); BufferedReader sin=new BufferedReader( new InputStreamReader(System.in)); String readline; System.out.print(\"Client:\"); readline=sin.readLine(); while(!readline.equals(\"bye\")){ } sin.close(); os.close(); is.close(); socket.close(); System.out.println(\"Error:\"+e); os.println(readline); os.flush(); System.out.println(\"Server:\"+is.readLine()); System.out.println(\"Client:\"); readline=sin.readLine(); }catch(Exception e){ 16. 要求:编写带图形界面的聊天程序,实现让客户可以持续地发送消息给服务器,服务器也可以即时看到客户端发送的消息,并回消息给客户端。程序运行界面如下: //服务器端程序如下: public class MyServer extends JFrame implements ActionListener { jb.addActionListener(this); jtf.addActionListener(this); JScrollPane jsp = new JScrollPane(jta); this.add(jsp, BorderLayout.CENTER); this.add(jp, BorderLayout.SOUTH); jp.add(jtf); jp.add(jb); public MyServer() { jta = new JTextArea(); jtf = new JTextField(15); jb = new JButton(\"发送\"); jp = new JPanel(); JTextArea jta; JTextField jtf; JButton jb; JPanel jp; ServerSocket ss; Socket socket; DataOutputStream out; DataInputStream in; } // 展现 this.setTitle(\"服务器\"); this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); // 开放端口 try { } ss = new ServerSocket(9000); System.out.println(\"等待连接\"); socket = ss.accept(); System.out.println(\"已连接\"); out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); while (true) { // 接受客户端发送数据 String str = in.readUTF(); // 显示多行文本框中 jta.append(\"客户端说:\" + str + \"\\r\\n\"); } e.printStackTrace(); } catch (IOException e) { public static void main(String[] args) { } public void actionPerformed(ActionEvent e) { if (e.getSource() == jb || e.getSource() == jtf) { } // 向客户端发送数据 try { } // 向多行文本框输入历史聊天记录信息 jta.append(\"服务器说:\" + jtf.getText() + \"\\r\\n\"); // 清空单行文本框内容 jtf.setText(\"\"); out.writeUTF(jtf.getText()); e1.printStackTrace(); } catch (IOException e1) { new MyServer(); } } //客户端程序如下: public class MyClient extends JFrame implements ActionListener { while (true) { // 接受服务器发送数据 String str = in.readUTF(); try { // 建立连接 socket = new Socket(\"127.0.0.1\ out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); // 展现 this.setTitle(\"客户端\"); this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); jb.addActionListener(this); jtf.addActionListener(this); JScrollPane jsp = new JScrollPane(jta); this.add(jsp, BorderLayout.CENTER); this.add(jp, BorderLayout.SOUTH); jp.add(jtf); jp.add(jb); public MyClient() { jta = new JTextArea(); jtf = new JTextField(15); jb = new JButton(\"发送\"); jp = new JPanel(); JButton jb; JTextArea jta; JTextField jtf; JPanel jp; Socket socket; DataOutputStream out; DataInputStream in; } } // 显示在多行文本框 jta.append(\"服务器说:\" + str + \"\\r\\n\"); } } catch (UnknownHostException e) { } e.printStackTrace(); e.printStackTrace(); } catch (IOException e) { public static void main(String[] args) { } public void actionPerformed(ActionEvent e) { } if (e.getSource() == jb || e.getSource() == jtf) { } // 向服务器发送数据 try { } // 显示在多行文本框 jta.append(\"客户端说:\" + jtf.getText() + \"\\r\\n\"); // 清空单行文本框 jtf.setText(\"\"); out.writeUTF(jtf.getText()); e1.printStackTrace(); } catch (IOException e1) { new MyClient(); 二.阅读并分析下面程序,给出程序的运行结果。 1. public class abc { public static void main(String[] args) { int i, s = 0; int a[] = { 11, 22, 33, 44, 55, 66, 77, 88, 99 }; for (i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { s += a[i]; System.out.println(\"s=\" + s); } } } } 答案: s=22 s=66 s=132 s=220 2.public class abc { public static void main(String[] args) { int i,k; int a[]={11,21,31,41,51,61,71,81,91}; for(i=0;i 答案: 11 31 41 61 71 3.public class BreakTab { public static void main(String[] args) { loop: for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { if (i * j > 16) { break loop; } System.out.print(i + \"*\" + j + \"=\" + i * j + \"\\"); } System.out.print(\"\\r\\n\"); } // 输出一个回车换行符 } } 答案: 1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 4. public class Example03 { public static void main(String args[]) { ComputerSum sum = new ComputerSum(); sum.computer1.start(); } } class ComputerSum implements Runnable { Thread computer1, computer2; int i = 1, sum = 0; ComputerSum() { computer1 = new Thread(this); computer2 = new Thread(this); } public void run() { while (i <= 10) { sum = sum + i; System.out.print(sum+\"\\"); i++; if (i == 6 && Thread.currentThread() == computer1) { System.out.println(); System.out.println(computer1.getName() + \"完成任务了!\"); computer2.start(); return; }}} } 答案: 1 3 6 10 15 Thread-0完成任务了! 21 28 36 45 55 5.public class Score { static StringprintArray(int[] a){ String result=\" \"; for(int i=0;i public static void main(String[] args) { int a[]={25,36,47,32,21,16}; System.out.println(\"before sort:\\n\"+ printArray(a)); a=bubbleSort(a); System.out.println(\"after sort:\\n\"+ printArray(a)); } } 答案: before sort: 25 36 47 32 21 16 after sort: 16 21 25 32 36 47 6.import java.util.Arrays; publicclass SortArray { } 答案: publicstaticvoid main(String args[]) { } String[] str = { \"size\", \"abs\", \"length\", \"class\" }; Arrays.sort(str); for (int i = 0; i < str.length; i++) System.out.print(str[i] + \" \"); System.out.println(); System.out.println(str[0].length()); abs class length size 3 7.publicclass lianxi02 { publicstaticvoid main(String[] args) { int count = 0; for (int i = 1; i < 20; i += 2) { boolean b = false; for (int j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { } b = false; break; b = true; } else { } } } if (b == true) { } count++; System.out.print(i + \" \"); System.out.println(\"\\n输出的元素个数为: \" + count); } 答案: 5 7 11 13 17 19 输出的元素个数为: 6 8.publicclass lianxi22 { } class rec { } 答案: publiclongrec(int n) { } long value = 0; if (n == 1) { } return value; value = 1; value = n * rec(n - 1); } else { publicstaticvoid main(String[] args) { } int n = 5; rec fr = new rec(); System.out.println(n + \"! = \" + fr.rec(n)); 5! = 120 因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务