?? myguessgame.java
字號:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.JFrame;
/**
* @author zzl
繼承JFrame類,并實現ActionListener監聽器接口。
*/
public class MyGuessGame extends JFrame implements ActionListener {
JTextField tf=new JTextField(); //聲明成員變量
JButton b1= new JButton("開局");
JLabel j1=new JLabel();
int m;//存放隨機數變量
int count;//存放次數變量
int oldNumber;//存放原有記錄次數變量
boolean isEnd;//標志是否破紀錄變量
//構造方法,完成圖形界面的初始化工作
public MyGuessGame() {
b1.setActionCommand("start");
JPanel p=new JPanel();
p.add(b1);
b1.addActionListener(this);
tf.addActionListener(this);
tf.setEnabled(false);
this.getContentPane().add(tf,"North");
this.getContentPane().add(j1);
this.getContentPane().add(p,"South");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300,200);
this.setLocation(300,300);
this.setVisible(true);
}
//產生隨機數的方法
public int getNumber() {
int m=(int)(Math.random()*100)+1;
return m;
}
//事件處理方法
public void actionPerformed (ActionEvent e) {
String s=e.getActionCommand();
int n=0;//存放用戶所猜數字的變量
//單擊“開局”按鈕后的處理
if(s.equals("start")){
isEnd=false;
count=0;
m=this.getNumber();
System.out.print(m);
b1.setEnabled(false);
tf.setEnabled(true);
j1.setText("請輸入1-100之間您猜的數");
tf.requestFocus();
oldNumber=readRecord();
}
else{
if(!isEnd){
count++;
String sn=tf.getText();
try{
n=Integer.parseInt(sn);
}catch(NumberFormatException el){
j1.setText("請輸入數字");
return;
}
if(n<m){
j1.setText("你猜的數偏小");
return;
}else if(n>m){
j1.setText("你猜的數偏大");
return;
}else{
j1.setText("恭喜您猜對了,所次數為"+count);
tf.setText("");
b1.setEnabled(true);
if(oldNumber>count){
j1.setText("您破記錄了,請在文本框輸入您的姓名");
isEnd=true;
}
}
}
else{
String name=tf.getText();
this.saveRecord(name,count);
j1.setText("您的記錄已經記錄在冊,繼續努力!");
tf.setText("");
b1.setEnabled(true);
}
}
}
public void saveRecord(String name,int count){
File f1=new File("record.txt");
try{
FileWriter fout=new FileWriter(f1);
PrintWriter bw=new PrintWriter(fout);
bw.println(count);
bw.println(name);
bw.close();
fout.close();
}catch(FileNotFoundException e){
}catch(IOException e){
}
}
public int readRecord()
{
int count=100;
File f1=new File("record.txt");
try{
FileReader fin=new FileReader(f1);
BufferedReader br=new BufferedReader(fin);
String s=br.readLine();
count =Integer.parseInt(s);
br.close();
fin.close();
}catch(FileNotFoundException e){
}catch(IOException e){
}
return count;
}
public static void main(String[] args) {
// TODO 自動生成方法存根
new MyGuessGame();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -