隨機選組

weixin_34321977發表於2010-06-23

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;


public class Pingpang extends Frame implements ActionListener{
    
Panel p,p1;
TextField tf;
Button bt1,bt2;
TextArea ta;
public static String[] str=new String[100];
public static int ii=0;
public static int k,q;

public Pingpang(){
   p=new Panel();
   p1=new Panel();
   tf=new TextField("");
   bt1=new Button("輸入姓名");
   bt2=new Button("開始選組");
   ta=new TextArea();
   ta.setEditable(false);
  
   bt1.addActionListener(this);
   bt2.addActionListener(this);
  
   p1.add(tf);
   p1.add(bt1);
   p1.add(bt2);
   add(p1,new BorderLayout().NORTH);
   p.add(ta);
   add(p,new BorderLayout().CENTER);
   setSize(500,500);
   setVisible(true);
  
   addWindowListener(new WindowAdapter(){
    public void windowActivated(WindowEvent e){
     bt1.requestFocus();
    }
    public void windowClosing(WindowEvent e){
     dispose();
    }
   });
    }

public void actionPerformed(ActionEvent e){
   if(e.getSource().equals(bt1)){
      String strr=tf.getText();
      str[ii]=strr;
      ii++;
      tf.setText("");
   }
   else if(e.getSource().equals(bt2)){
    ta.setText("");
    int count=ii;
    while(count>=2){
     Choosetwo();
             count-=2;
    }

            for(int i=0;i<=ii;i++){
            if(str[i]!=null){
               ta.append(str[i]+"----");
               str[i]=null;
            }                     
            }
           ii=0; 
   }
  
}

public void Choosetwo(){
   k=(int)(Math.random()*ii);
   q=(int)(Math.random()*ii);
   while(str[k]==null||str[q]==null||k==q){
    q=(int)(Math.random()*ii);
    k=(int)(Math.random()*ii);
   }
   ta.append(str[k]+"----"+str[q]+'\n'); 
   str[k]=null;
   str[q]=null;
}

public static void main(String args[]){
   Pingpang p=new Pingpang();
}
}

相關文章