Java 2实用教程(第三版)实验指导与习题解答and实验模版代码及答案 (三)

时间:2023-02-25 10:05:01

实验1  扫雷小游戏
1.答案:

【代码1】:  new LinkedList();

【代码2】:  list.add(block[i][j]) ;        

【代码3】:  list.size();              

【代码4】:  (Block)list.get(randomIndex);

【代码5】:  list.remove(randomIndex);     

2.模板代码

Block.java

public class Block

{ String name;

  int number;

  boolean boo=false;

  public void setName(String name)

  { this.name=name;

  }

  public void setNumber(int n)

  { number=n;

  }

  public int getNumber()

  { return number;

  }

  public String getName()

  { return name; 

  }

  boolean isMine()

  { return boo;

  }

  public void setIsMine(boolean boo)

  { this.boo=boo;

  }

}

LayMines.java

import java.util.LinkedList;

public class LayMines

{   public void layMinesForBlock(Block block[][],int mineCount)

    {   int row=block.length;

        int column=block[0].length;

        LinkedList list=【代码1】 //创建空链表list

        for(int i=0;i<row;i++)

        { for(int j=0;j<column;j++)

            { 【代码2】 // list添加节点,其中的数据为block[i][j]

            }

        }

       while(mineCount>0)

        {   int size=【代码3】 // list返回节点的个数

            int randomIndex=(int)(Math.random()*size);

            Block b=【代码4】 // list返回索引为randomIndex的节点中的数据

            b.setName("雷");

            b.setIsMine(true);

            【代码5】        //list删除索引值为randomIndex的节点

            mineCount--;

        }

       for(int i=0;i<row;i++)

        { for(int j=0;j<column;j++)

           { if(block[i][j].isMine()){}

             else

              {  int mineNumber=0;

                 for(int k=Math.max(i-1,0);k<=Math.min(i+1,row-1);k++)

                   { for(int t=Math.max(j-1,0);t<=Math.min(j+1,column-1);t++)

                       {   if(block[k][t].isMine())

                              mineNumber++;        

                       }

                   }

                 block[i][j].setName(""+mineNumber);

                 block[i][j].setNumber(mineNumber);

              }

           }

        }   

    }

}

BlockView.java

import java.awt.*;

public class BlockView extends Panel

{  Label blockName;

   Button blockCover;

   CardLayout card;

   BlockView()

   { card=new CardLayout();

     setLayout(card);

     blockName=new Label();

     blockCover=new Button();

     add("cover",blockCover);

     add("name",blockName);

   }

  public void setName(String name)

   { blockName.setText(name);

   }

  public String getName()

   {  return blockName.getText();

   }

  public void seeBlockName()

   {  card.show(this,"name");

      validate();

   }

  public void seeBlockCover()

   {  card.show(this,"cover");

      validate();

   }

  public Button getBlockCover()

   {  return blockCover;

   }

}

MineFrame.java

import java.awt.*;

import java.awt.event.*;

public class MineFrame extends Frame implements ActionListener

{  Button reStart;

   Block block[][];

   BlockView blockView[][];

   LayMines lay;

   int row=10,colum=12,mineCount=22;

   int colorSwitch=0;

   Panel pCenter,pNorth;

   public MineFrame()

   {   reStart=new Button("重新开始");

       pCenter=new Panel();

       pNorth=new Panel();

       pNorth.setBackground(Color.cyan);

       block=new Block[row][colum];

       for(int i=0;i<row;i++)

       {  for(int j=0;j<colum;j++)

            {  block[i][j]=new Block();

            }

       }

       lay=new LayMines();

       lay.layMinesForBlock(block,mineCount);   

       blockView=new BlockView[row][colum];

       pCenter.setLayout(new GridLayout(row,colum));

       for(int i=0;i<row;i++)

       { for(int j=0;j<colum;j++)

            {  blockView[i][j]=new BlockView();

               blockView[i][j].setName(block[i][j].getName());

               pCenter.add(blockView[i][j]);

               blockView[i][j].getBlockCover().addActionListener(this);

            }

       }

      reStart.addActionListener(this);

      pNorth.add(reStart);

      add(pNorth,BorderLayout.NORTH);

      add(pCenter,BorderLayout.CENTER);

      setSize(200,232);

      setVisible(true);

      addWindowListener(new WindowAdapter()

            {  public void windowClosing(WindowEvent e)

               {  System.exit(0);

               }

            });

      validate();

   }

  public void actionPerformed(ActionEvent e)

   {  Button source=(Button)e.getSource();

      if(source!=reStart)  

      { int m=-1,n=-1;

        for(int i=0;i<row;i++)

        { for(int j=0;j<colum;j++)

          { if(source==blockView[i][j].getBlockCover())

              { m=i;

                n=j;

                break;

              }

          }

        }

       if(block[m][n].isMine())

        {  for(int i=0;i<row;i++)

          {  for(int j=0;j<colum;j++)

             {  blockView[i][j].getBlockCover().removeActionListener(this);

                if(block[i][j].isMine())

                  blockView[i][j].seeBlockName();

             }

          }

        }

       else

        {  if(block[m][n].getNumber()>0)

             blockView[m][n].seeBlockName();

           else if(block[m][n].getNumber()==0)

           for(int k=Math.max(m-1,0);k<=Math.min(m+1,row-1);k++)

            { for(int t=Math.max(n-1,0);t<=Math.min(n+1,colum-1);t++)

               {  blockView[k][t].seeBlockName();

               }     

            }

        }

      }

      if(source==reStart)

      {  for(int i=0;i<row;i++)

         { for(int j=0;j<colum;j++)

            {  block[i][j].setIsMine(false);

            }

         }

         lay.layMinesForBlock(block,mineCount);

         for(int i=0;i<row;i++)

         { for(int j=0;j<colum;j++)  

            {  blockView[i][j].setName(block[i][j].getName());

               blockView[i][j].seeBlockCover();

               blockView[i][j].getBlockCover().addActionListener(this);

            }

         }

      }

   }

}

MineExample.java

public class LayMineMainClass

{  public static void main(String args[])

   {  new MineFrame();

   }

}

实验2  排序与查找
2.模板代码

Book.java

public class Book implements Comparable

{  double price;

   String name;

   public void setPrice(double c)

   {  price=c;

   }

   public double getPrice()

   {  return price;

   }

   public void setName(String n)

   {  name=n;

   }

   public String getName()

   {  return name;

   }

   public int compareTo(Object object)

   {  Book bk=(Book)object;

      int difference=(int)((this.getPrice()-bk.getPrice())*10000);

      return  difference;

   }

}

SortSearchMainClass.java

import java.util.*;

public class SortSearchMainClass

{  public static void main(String args[])

   {  LinkedList bookList=new LinkedList();

      String bookName[]={"Java编程","XML基础","JSP基础","C++基础",

"J2ME编程","操作系统","数据库技术"};

      double bookPrice[]={29,21,22,29,34,32,29};

      Book book[]=new Book[bookName.length];

      for(int k=0;k<book.length;k++)

      {  book[k]=new Book();

         book[k].setName(bookName[k]);

         book[k].setPrice(bookPrice[k]);

         bookList.add(book[k]);

      }

     Book newBook=new Book();

     newBook.setPrice(29);

     newBook.setName("Java与模式");

     Collections.sort(bookList);

     int m=-1;

     System.out.println("新书:"+newBook.getName()+"("+newBook.getPrice()+

")与下列图书:");

     while((m=Collections.binarySearch(bookList,newBook))>=0)

     {   Book bk=(Book)bookList.get(m);

         System.out.println(" "+bk.getName()+"("+bk.getPrice()+")");

         bookList.remove(m);

     }

     System.out.println("价钱相同");

   }

}

实验3  使用TreeSet排序
1.答案:

【代码1】:  new TreeSet();

【代码2】:  treeSet.add(stu);         

【代码3】:  tree.iterator();             

【代码4】:  te.hasNext()

【代码5】:  (Student)te.next();     

2.模板代码

Student.java

public class Student implements Comparable

{  String name;

   int score;

   Student(String name,int score)

   {  this.name=name;

      this.score=score;

   }

   public int compareTo(Object b)

   {  Student st=(Student)b;

      int m=this.score-st.score;

      if(m!=0)

       return m;

      else

       return 1;

   }

  public int getScore()

   {  return score;

   }

  public String getName()

   {  return name;

   }

}

StudentFrame.java

import java.awt.*;

import java.awt.event.*;

import java.util.*;

public class StudentFrame extends Frame implements ActionListener

{   TextArea showArea;

    TextField inputName,inputScore;

    Button button;

    TreeSet treeSet;

    StudentFrame()

    {  treeSet=【代码1】 //使用无参数构造方法创建treeSet

       showArea=new TextArea();

       showArea.setFont(new Font("",Font.BOLD,20));

       inputName=new TextField(5);

       inputScore=new TextField(5);

       button=new Button("确定");

       button.addActionListener(this);

       Panel pNorth=new Panel();

       pNorth.add(new Label("Name:"));

       pNorth.add(inputName);

       pNorth.add(new Label("Score:"));

       pNorth.add(inputScore);

       pNorth.add(button);

       add(pNorth,BorderLayout.NORTH);

       add(showArea,BorderLayout.CENTER);

       setSize(300,320);

       setVisible(true);

       addWindowListener(new WindowAdapter()

            {  public void windowClosing(WindowEvent e)

               {  System.exit(0);

               }

            });

       validate();

    }

   public void actionPerformed(ActionEvent e)

    {  String name=inputName.getText();

       int score=0;

       try{ score=Integer.parseInt(inputScore.getText().trim());

            if(name.length()>0)

            {  Student stu=new Student(name,score);

               【代码2】 // treeSet添加stu

               show(treeSet);

            }

          }

       catch(NumberFormatException exp)

          {  inputScore.setText("请输入数字字符");

          }

    }

  public void show(TreeSet tree)

    {  showArea.setText(null);

       Iterator te=【代码3】 // treeSet 返回迭代器

       while(【代码4】)     //te判断是否有下一个元素

       {  Student stu=【代码5】 // te返回其中的下一个元素

          showArea.append("Name:"+stu.getName()+" Score: "+stu.getScore()+"\n");

       }

    }

}

TreeSetMainClass.java

public class TreeSetMainClass

{  public static void main(String args[])

   {  new StudentFrame();

   }

}

 

上机实践12  java Swing
实验1  JLayeredPane分层窗格
1.答案:

【代码1】:  pane.add(b5,JLayeredPane.DRAG_LAYER);

【代码2】:  pane.add(b4,JLayeredPane.POPUP_LAYER);        

【代码3】:  pane.add(b3,JLayeredPane.MODAL_LAYER);              

【代码4】:  pane.add(b2,JLayeredPane.PALETTE_LAYER);

【代码5】:  pane.add(b1,JLayeredPane.DEFAULT_LAYER);     

2.模板代码

import javax.swing.*;

import java.awt.*;

class LayerExample

{   public static void main(String args[])

    {  JFrame win=new JFrame("窗体");

       win.setBounds(100,100,300,300);

       win.setVisible(true);

       JButton b1=new JButton("我在DEFAULT_LAYER"),

              b2=new JButton("我在PALETTE_LAYER"),

               b3 =new JButton("我在MODAL_LAYER"),

               b4 =new JButton("我在POPUP_LAYER"),

               b5=new JButton("我在DRAG_LAYER");

       Container contenetPane=win.getContentPane();

       JLayeredPane pane= new JLayeredPane();

       pane.setLayout(null);

       【代码1】 //pane将组件b5放置在DRAG_LAYER层

       【代码2】 //pane将组件b4放置在POPUP_LAYER层

       【代码3】 //pane将组件b3放置在MODAL_LAYER层

       【代码4】 //pane将组件b2放置在PALETTE_LAYER层

       【代码5】 //pane将组件b3放置在DEFAULT_LAYER层

       b5.setBounds(50,50,200,100);        

       b4.setBounds(40,40,200,100);

       b3.setBounds(30,30,200,100);

       b2.setBounds(20,20,200,100);

       b1.setBounds(10,10,200,100);

       b1.setBackground(Color.red);

       b2.setBackground(Color.pink);

       b3.setBackground(Color.green);

       b4.setBackground(Color.orange);

       b5.setBackground(Color.yellow);

       contenetPane.add(pane,BorderLayout.CENTER);

       contenetPane.validate();

       win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

实验2  使用表格显示日历
1.答案:

【代码1】:  table=new JTable(rili,name);

【代码2】:  table=new JTable(rili,name);       

【代码3】:  table=new JTable(rili,name);             

2.模板代码

CalendarBean.java

import java.util.Calendar;

public class CalendarBean

{  int year=2005,month=0,nextDay;

   public void setYear(int year)

   {  this.year=year;

   }

   public int getYear()

   {  return year;

   }

   public void setMonth(int month)

   {  this.month=month;

   }

   public int getMonth()

   {  return month;

   }

   public String[][] getCalendar()

   {   String a[][]=new String[6][7];         

       Calendar 日历=Calendar.getInstance();

       日历.set(year,month-1,1);            

       int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;

       int day=0;

     if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)

      {  day=31;

      }

     if(month==4||month==6||month==9||month==11)

      {  day=30;

      }

     if(month==2)

      { if(((year%4==0)&&(year%100!=0))||(year%400==0))

           {  day=29;

           }

         else

           {  day=28;

           }

      }

      nextDay=1;

      for(int k=0;k<6;k++)

      {  if(k==0)

           for(int j=星期几;j<7;j++)

           {    a[k][j]=" "+nextDay ;

                nextDay++;

           }

         else

           for(int j=0;j<7&&nextDay<=day;j++)

           {    a[k][j]=""+nextDay ;

                nextDay++;

           }

      }

      return a;

   }

}

CalenderFrame.java

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class CalenderFrame extends JFrame implements ActionListener

{    JTable table;

     Object name[]={"星期日","星期一","星期二","星期三", "星期四","星期五","星期六"};

     JButton  nextMonth,previousMonth;

     int year=2006,month=5;

     CalendarBean calendar;

     String rili[][];

     JLabel showMessage=new JLabel("",JLabel.CENTER);

     JScrollPane scroll;

     public  CalenderFrame()

     {  calendar=new  CalendarBean();

        calendar.setYear(year);

        calendar.setMonth(month);

        rili=calendar.getCalendar();

        【代码1】 //使用数组rili和name创建table

        table.setRowSelectionAllowed(false);

        nextMonth=new JButton("下月");

        previousMonth=new JButton("上月");

        nextMonth.addActionListener(this);

        previousMonth.addActionListener(this);

        JPanel pNorth=new JPanel(),

               pSouth=new JPanel();

        pNorth.add(previousMonth);

        pNorth.add(nextMonth);

        pSouth.add(showMessage);

        showMessage.setText("日历:"+calendar.getYear()+"年"+calendar.getMonth()+

"月" );

        scroll=new JScrollPane(table);

        add(scroll,BorderLayout.CENTER);

        add(pNorth,BorderLayout.NORTH);

        add(pSouth,BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setBounds(100,100,400,240);

        setVisible(true);

        validate();

     }

     public void actionPerformed(ActionEvent e)

     {  if(e.getSource()==nextMonth)

        { month=month+1;

          if(month>12)

              month=1;

          calendar.setMonth(month);

          rili=calendar.getCalendar();

          remove(scroll);

          【代码2】 //使用数组rili和name创建table

table.setRowSelectionAllowed(false);

          scroll=new JScrollPane(table);

          add(scroll,BorderLayout.CENTER);

        }

      else if(e.getSource()==previousMonth)

        { month=month-1;

          if(month<1)

              month=12;

          calendar.setMonth(month);

          rili=calendar.getCalendar();

          remove(scroll);

          【代码3】 //使用数组rili和name创建table

table.setRowSelectionAllowed(false);

          scroll=new JScrollPane(table);

          add(scroll,BorderLayout.CENTER);

        }

       showMessage.setText("日历:"+calendar.getYear()+"年"+calendar.getMonth()+"月" );

     }

}

CalendarMainClass.java

public class CalendarMainClass

{  public static void main(String args[])

   {  new CalenderFrame();

   }

}

实验3  多文档界面(MDI)
1.答案:

【代码1】:  new JDesktopPane();

【代码2】:  desk.getAllFrames();       

【代码3】:  desk.setLayer(a[i],JDesktopPane.DEFAULT_LAYER);             

【代码4】:  desk.add(newInternalFrame,JDesktopPane.DRAG_LAYER);

2.模板代码

MDIExample.java

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

class MyInternalFrame extends  JInternalFrame

{   JTextArea text;

    MyInternalFrame(String title)

    {  super(title,true,true,true,true);

       text=new JTextArea();

       Container con=getContentPane();

       con.add(new JScrollPane(text),BorderLayout.CENTER);

       setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

       addInternalFrameListener(new InternalFrameAdapter ()

                      { public void internalFrameActivated(InternalFrameEvent e)

                           { setLayer(JDesktopPane.DRAG_LAYER);

                           }

                        public  void internalFrameDeactivated(InternalFrameEvent e)

                           { setLayer(JDesktopPane.DEFAULT_LAYER);

                           }

                       });

    }

    public JTextArea getJTextArea()

    {  return text;

    }

}

class Mywindow extends JFrame implements ActionListener

{   JDesktopPane  desk;    

    JMenuBar menubar;

    JMenu menu;

    JMenuItem  itemNew,itemCopy,itemCut,itemPaste;

    Container con;

    Mywindow()

    {  setSize(360,360);

       setVisible(true);

       con=getContentPane();

       desk=【代码1】 //创建JdesktopPane对象。

       desk.setDesktopManager(new DefaultDesktopManager());

       con.add(desk,BorderLayout.CENTER);

       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       menubar=new JMenuBar();

       menu=new JMenu("编辑");  

       itemNew=new JMenuItem("新建");

       itemCopy=new JMenuItem("拷贝");

       itemCut=new JMenuItem("剪切");

       itemPaste=new JMenuItem("粘贴");

       itemNew.addActionListener(this);

       itemCopy.addActionListener(this);

       itemCut.addActionListener(this);

       itemPaste.addActionListener(this);

       menu.add(itemNew);

       menu.add(itemCopy);

       menu.add(itemCut);

       menu.add(itemPaste);

       menubar.add(menu);

       setJMenuBar(menubar);

       validate();

    }

   public void actionPerformed(ActionEvent e)

    {  if(e.getSource()==itemNew)        

       {  JInternalFrame a[]=【代码2】//desk返回其中的全部内部窗体

          for(int i=0;i<a.length;i++)

           { 【代码3】     //desk 将a[i]放置在DEFAULT_LAYER层

           }

          JInternalFrame newInternalFrame=new  MyInternalFrame("无标题");

          newInternalFrame.setBounds(10,10,300,300);

          newInternalFrame.setVisible(true);

          【代码4】       //desk 将newInternalFrame放置在DRAG_LAYER层

          desk.validate();

          con.validate();

          this.validate();

       }

      if(e.getSource()==itemCopy)

       {   MyInternalFrame internalFrame=(MyInternalFrame)desk.getSelectedFrame();

           JTextArea text=internalFrame.getJTextArea();

           text.copy();

       }  

       else if(e.getSource()==itemCut)

       {   MyInternalFrame internalFrame=(MyInternalFrame)desk.getSelectedFrame();

           JTextArea text=internalFrame.getJTextArea();

           text.cut();

       }   

       else if(e.getSource()==itemPaste)

       {   MyInternalFrame internalFrame=(MyInternalFrame)desk.getSelectedFrame();

           JTextArea text=internalFrame.getJTextArea();

           text.paste();

       }

    }

}

public class MDIExample

{  public static void main(String args[])

    {  Mywindow win=new Mywindow();

    }

}