第三届全国ITAT教育工程就业技能大赛复赛试题 Java程序设计(B卷)答案

来源:互联网 发布:js this的作用域 编辑:程序博客网 时间:2024/04/28 05:14


      

1、   编写一个Java应用程序,对用户输入的任意一组字符如{1,3,4,7,2,1,1,5,2},输出其中出现次数最多且数值最大的字符,并显示其出现次数。(本题20分)

package programming; public class CountChar {    public static void main(String[] args) {      int[] ori={1,3,4,7,2,1,1,5,2};      int ori_len=ori.length;      int[] count=new int[ori_len];      int[] most=new int[ori_len];      int count_max=count[0];      int most_max=most[0];           for(int i=0;i<ori_len;i++)          for(intj=0;j<ori_len;j++)             if(ori[i]==ori[j])                count[i]++;           //查看各个数字出现的次数      for(int i=0;i<count.length;i++)            System.out.print(count[i]);           System.out.print("\n");             //求得count数组的最大值      for(int i=1;i<count.length;i++)         if(count_max<count[i])            count_max=count[i];           //求得count最大值count[i]对应的m[i](m[i]可能有多个)      for(inti=0,j=0;i<count.length;i++)         if(count[i]==count_max)            most[j++]=ori[i];//将出现次数最多的ori[i]赋给most数组(ori[i]可能有多个)           //得到most数组的最大值,      for(int i=1;i<most.length;i++)         if(most_max<most[i])            most_max=most[i];           System.out.print(most_max);   } }


2、   编写一个Java应用程序,使用Java的输入输出流技术将Input.txt的内容逐行读出,每读出一行就顺序为其添加行号(从1开始,逐行递增),并写入到另一个文本文件Output.txt中。(本题20分)

package programming; import java.io.*;public class ReadTxt {    public static void main(String[] args) {      try{         String str;         int i=1;      BufferedReader br=new BufferedReader            (new InputStreamReader(new FileInputStream("D:\\Java\\javaCompetition\\input.txt")));      BufferedWriter bw=new BufferedWriter            (new OutputStreamWriter(new FileOutputStream("D:\\Java\\javaCompetition\\output.txt")));           while((str=br.readLine())!=null)      {         bw.write(String.valueOf(i++));         bw.write(str);         bw.newLine();      }      br.close();      bw.close();      }catch(FileNotFoundException e){e.printStackTrace();}      catch(IOException e){e.printStackTrace();}   } } 


3、   编写一个Java应用程序,使用RandomAccessFile流统计Hello.txt中的单词,要求如下:

(1)计算全文中共出现了多少个单词(重复的单词只计算一次);

(2)统计出有多少个单词只出现了一次;

(3)统计并显示出每个单词出现的频率,并将这些单词按出现频率高低顺序显示在一个TextArea中。(本题30分)

package programming;import java.io.*;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.Map.Entry;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern; public class CountTxtNumber {    @SuppressWarnings("unchecked")   public static void main(String[] args) {           String str,word="";      String[] words;      int count,count_once=0;      HashMap<String,Integer> hm=new HashMap<String,Integer>();      try{      RandomAccessFile raf=new RandomAccessFile            ("D:\\Java\\javaCompetition\\hello.txt","r");       while((str=raf.readLine())!=null)      {         //以下三行将把str中的所有英文标点符号去掉           Pattern p=Pattern.compile("[,.?!\\\"\']");         Matcherm=p.matcher(str);         str=m.replaceAll("");                 //以“ ”为标记将str分割,得到的结果(一个数组)赋值给words         words=str.split(" ");          /*遍历words数组,以单词为键值、单词出现次数为值。          * 逐个添加单词(words[i]),若单词已存在,次数(count)加1;                              若单词不存在,次数赋值为1      */         for(int i=0;i<words.length;i++)            if(hm.containsKey(words[i]))            {              count=hm.get(words[i]).intValue();               hm.put(words[i],count+1);            }            else               hm.put(words[i],1);              }      //得到全文中共出现的单词的个数(重复的单词只计算一次)      System.out.println(hm.size());           //由hm.entrySet()得到entryset(此即为HashMap的所有键值对的集合)        Set<Entry<String, Integer>>entryset=hm.entrySet();                //创建entryset的迭代器it      Iterator<Entry<String, Integer>>it=entryset.iterator();      while(it.hasNext())      {         if(it.next().getValue()==1)//若出现次数为1则count_once自加1            count_once++;         //统计出现次数为1的单词个数      }      System.out.println(count_once);             //将由hm.entrySet()得来的entryset按照频率大小由前到后排序      ArrayList<Entry<String, Integer>> al=            new ArrayList<Entry<String, Integer>>(entryset);           //Collections.sort(List<T>arg0, Comparator arg1)方法      Collections.sort(al, new Comparator()      {public int compare(Object o1,Object o2){         Entry<String,Integer>ent1=(Entry<String,Integer>)o1;         Entry<String,Integer>ent2=(Entry<String,Integer>)o2;         return ent2.getValue()-ent1.getValue();      }});             //得到排序后的ArrayList的迭代器       Iteratoriter=al.iterator();             while(iter.hasNext())       {          Entry<String, Integer> ent=(Entry<String,Integer>)(iter.next());          System.out.print(ent.getKey()+":");          System.out.println(ent.getValue());       }       raf.close();      }catch(FileNotFoundExceptione)      {e.printStackTrace();}      catch(IOException e){e.printStackTrace();}      } }


 

4、   编写一个Java GUI应用程序,采用Java多线程技术,有两个线程,模拟垂直上抛运动和水平抛体运动:一个球垂直上抛,一个球水平抛出。(本题30分)

(垂直上抛物理公式:h=v0*t-g*t2/2 ;平抛运动物理公式:h=g*t2/2 ,x=v*t ;

h代表高度,v0代表初速度=30m/s ,t代表时间,g代表重力加速度=9.8 m/s2 ,v代表平抛速度=30m/s )

package programming;import java.awt.Color;import java.awt.Graphics; import javax.swing.*; public class GuiMultiThread2 extends JFrame{    public GuiMultiThread2()   {      DrawBall db=new DrawBall();      this.add(db);      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      this.setSize(700, 400);      this.setVisible(true);      Thread thread=new Thread(db);      thread.start();   }     public static void main(String[] args) {      new GuiMultiThread2();    } }class DrawBall extends JPanel implements Runnable{/*  int Radius=30;*/   double heightV,heightH,xV,xH;   double time;   public void paintComponent(Graphics g)  {    //height=30*time-9.8*time*time/2;     heightV=9.8*time*time/2-30*time+100;     heightH=9.8*time*time/2;     xH=30*time;     super.paintComponent(g);     g.setColor(Color.BLUE);     g.fillOval((int)xV, (int)heightV, 20, 20);     g.setColor(Color.RED);     g.fillOval((int)xH, (int)heightH, 20, 20);  }  public void run()  {     try {      while(true)      {         time=time<15?time+0.5:0;         repaint();          Thread.sleep(250);      }   } catch (InterruptedException e) {      // TODO Auto-generatedcatch block      e.printStackTrace();   }      } }


 

 

附加题:

 

5、   编写一个Java应用程序,当用户在输入对话框中输入两个日期后(日期格式为YYYYMMDD,如1999年1月12日应输入为19990112),程序将判断两个日期的先后顺序,以及两个日期之间的间隔天数(例如1999年1月1日和1999年1月2日之间的间隔是1天)。(本题20分)

package programming; import java.util.Calendar;import java.util.GregorianCalendar;import javax.swing.JOptionPane; public class CalendarTest{   public static void main(String[] args)   {      String str1=JOptionPane.showInputDialog(null,            "请输入第一个日期(日期格式为YYYYMMDD,如1999年1月12日应输入为19990112):");      String str2=JOptionPane.showInputDialog(null,            "请输入第二个日期(日期格式为YYYYMMDD,如1999年1月12日应输入为19990112):");           Calendar calendar1=new GregorianCalendar();      Calendar calendar2=new GregorianCalendar();      calendar1.set(Integer.parseInt(str1.substring(0, 4)),            Integer.parseInt(str1.substring(4, 6)),Integer.parseInt(str1.substring(6,8)));      calendar2.set(Integer.parseInt(str2.substring(0, 4)),            Integer.parseInt(str2.substring(4, 6)),Integer.parseInt(str2.substring(6,8)));        long mills1=calendar1.getTimeInMillis();      long mills2=calendar2.getTimeInMillis();      long interval=0;      if(mills1<mills2){          System.out.println("第一个日期先于第二个日期");      interval=(mills2-mills1)/(24*3600*1000);      }      else if(mills1>mills2){         System.out.println("第二个日期先于第一个日期");      interval=(mills1-mills2)/(24*3600*1000);      }      else         System.out.println("两个日期相等");      System.out.println("两个日期的间隔是:"+interval+" 天");        }}


6、   编写客户/服务器程序,客户端Client.java使用DatagramSocket对象将数据包发送到服务器,请求获取服务器端的图像(考生可自选图像文件)。服务器端Server.java将图像文件包装成数据包,并使用DatagramSocket对象将该数据包发送到客户端。首先将服务器端的程序编译通过,并运行起来,等待客户的请求。(本题30分)


 

CODE [Client.java]package programming; import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.util.Arrays; import javax.swing.*; public class Client extends JFrame implementsActionListener{   private byte[] bytes=new byte[30000];   private JButton getImg=new JButton("获取服务器图像");   private ImageIcon img;   private JLabel jl=new JLabel();   private InetAddress address;   private DatagramSocket ds_client;   private DatagramPacket dp_receive;   private DatagramPacket dp_send;   public Client()   {      try{      ds_client=new DatagramSocket();       dp_receive=new DatagramPacket(bytes,bytes.length);       address=InetAddress.getByName("127.0.0.1");             //为客户端建立一个用来发送数据的分组,address(目标机器地址)为本机的127.0.0.1      dp_send=new DatagramPacket(bytes,bytes.length,address,8000);           getImg.addActionListener(this);      this.add(getImg,BorderLayout.NORTH);      this.add(jl,BorderLayout.CENTER);      this.setLocationRelativeTo(null);      this.setSize(300, 300);      this.setVisible(true);      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      }      catch(IOException ie)      {ie.printStackTrace();}   }    public void actionPerformed(ActionEvent e)   {      if(e.getSource()==getImg)      {      try{         /*Arrays.fill(bytes,(byte)0);*/      ds_client.send(dp_send);           ds_client.receive(dp_receive);                img=new ImageIcon(dp_receive.getData());      jl.setIcon(img);             }catch(IOException ie)      {ie.printStackTrace();}      }   }    public static void main(String[] args)   {      new Client();   }}   [Server.java] package programming; import java.io.FileInputStream;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;import java.util.Arrays; import javax.swing.ImageIcon; public class Server {   private byte[] bytes=new byte[1024];   private ImageIcon img=new ImageIcon("D:\\Java\\javaCompetition\\1.jpg");      public Server(){   try {           DatagramSocket ds_server=new DatagramSocket(8000);      DatagramPacket dp_receive=new DatagramPacket(bytes,bytes.length);      DatagramPacket dp_send=new DatagramPacket(bytes,bytes.length);      while(true){              ds_server.receive(dp_receive);      System.out.println("客户的地址:"+dp_receive.getAddress());           dp_send.setAddress(dp_receive.getAddress());      dp_send.setPort(dp_receive.getPort());           //将要发送到客户端的图片数据转换成byte型并设置数据包分组dp_send的数据      FileInputStream fis=new FileInputStream("D:\\Java\\javaCompetition\\1.jpg");      byte[] ImgData=new byte[fis.available()];      while((fis.read(ImgData,0,ImgData.length))!=-1)         dp_send.setData(ImgData);      fis.close();            //发送分组      ds_server.send(dp_send);      System.out.println("正在等待");           }   }  catch (IOException e) {           e.printStackTrace();   }}    public  static void main(String[] args)    {       new Server();    }}

 

原创粉丝点击