用java将以下这段代码与图形界面结合起来package chap02; import java.util.*; public class GuessNumber { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int targetNumber=(int)(Math.random()*10)+1; int guessCount=0;int maxTryTime=5; for(int i=0;i<maxTryTime;i++) { try { System.out.print("请输入一个0~10之间的数字:"); int guessNumber= sc.nextInt(); guessCount++; if(guessCount<maxTryTime) {int a=maxTryTime; int c=a-i-1; if(guessNumber>targetNumber) { System.out.println("数人的过大,您还有"+c+"次机会"); continue; } else if(guessNumber<targetNumber) { System.out.println("数人的过小,您还有"+c+"次机会"); continue; } else { System.out.println("恭喜你,猜对了!"); System.out.print("你一共猜了"+guessCount+"次"); break; } } if(guessCount<maxTryTime) { System.out.println("抱歉游戏失败"); } } catch(Exception e) { System.out.println("输入异常,请重新输入!!!"); } } }}
时间: 2024-01-16 22:02:54 浏览: 59
好的,以下是一个简单的Java Swing实现,将上述代码与图形界面结合起来。代码创建了一个包含文本框、标签、按钮和消息框的GUI,以便用户可以输入猜测数字,查看游戏进度和结果。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessNumberGUI extends JFrame implements ActionListener {
private JLabel promptLabel, resultLabel;
private JTextField inputField;
private JButton guessButton;
private int targetNumber, guessCount, maxTryTime;
public GuessNumberGUI() {
targetNumber = (int)(Math.random()*10)+1;
guessCount = 0;
maxTryTime = 5;
promptLabel = new JLabel("请输入一个0~10之间的数字:");
inputField = new JTextField(10);
guessButton = new JButton("猜!");
guessButton.addActionListener(this);
resultLabel = new JLabel("");
JPanel panel = new JPanel();
panel.add(promptLabel);
panel.add(inputField);
panel.add(guessButton);
panel.add(resultLabel);
this.add(panel);
this.setTitle("猜数字游戏");
this.setSize(300, 150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String inputText = inputField.getText();
try {
int guessNumber = Integer.parseInt(inputText);
guessCount++;
if (guessCount < maxTryTime) {
int c = maxTryTime - guessCount;
if (guessNumber > targetNumber) {
resultLabel.setText("数人的过大,您还有" + c + "次机会");
} else if (guessNumber < targetNumber) {
resultLabel.setText("数人的过小,您还有" + c + "次机会");
} else {
resultLabel.setText("恭喜你,猜对了!你一共猜了" + guessCount + "次");
guessButton.setEnabled(false);
}
} else {
resultLabel.setText("抱歉游戏失败");
guessButton.setEnabled(false);
}
} catch (NumberFormatException ex) {
resultLabel.setText("输入异常,请重新输入!!!");
}
}
public static void main(String[] args) {
new GuessNumberGUI();
}
}
```
希望这能帮到您!
阅读全文