📄 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 + -