gpt4 book ai didi

java - 组合锁 (Java)

转载 作者:行者123 更新时间:2023-12-01 14:45:26 26 4
gpt4 key购买 nike

我需要创建一项学校作业。以下是信息:创建一个包含十个按钮的框架,标记为 0 到 9。要退出程序,用户必须按顺序单击正确的三个按钮,例如 7-3-5。如果使用了错误的组合,框架会变成红色。

我已经通过在线研究帮助完成了框架和按钮,但我就是无法使功能正常工作。请查看我的代码并提前致谢。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ComboNumber extends JFrame implements ActionListener{

//variable declaration
int ans1 = 3;
int ans2 = 7;
int ans3 = 1;
int one, two, three;
String inData1, inData2, inData3;
JButton[] button;

//constructs the combolock object
public ComboNumber()
{
//sets flowlayout
getContentPane().setLayout(new FlowLayout());
Container c = getContentPane();
//creates buttons
button = new JButton[10];
for(int i = 0; i < button.length; ++i) {
button[i] = new JButton("" + i);
//adds buttons to the frame
c.add(button[i]);
//registers listeners with buttons
button[i].addActionListener(this);
}

//sets commands for the buttons (useless)

//sets title for frame
setTitle("ComboLock");
}
//end combolock object

//listener object
public void actionPerformed(ActionEvent evt)
{
Object o = evt.getSource();
for(int i = 0; i < button.length; ++i) {
if(button[i] == o) {
// it is button[i] that was cliked
// act accordingly
return;
}
}
}
//end listener object

//main method
public static void main (String[] args)
{
//calls object to format window
ComboNumber frm = new ComboNumber();

//WindowQuitter class to listen for window closing
WindowQuitter wQuit = new WindowQuitter();
frm.addWindowListener(wQuit);

//sets window size and visibility
frm.setSize(500, 500);
frm.setVisible(true);
}
//end main method
}
//end main class

//window quitter class
class WindowQuitter extends WindowAdapter
{
//method to close the window
public void windowClosing(WindowEvent e)
{
//exits the program when the window is closed
System.exit(0);
}
//end method
}
//end class

最佳答案

基本思想很简单。

你需要两件事。

  1. 实际的组合是什么
  2. 用户猜测了什么

所以。您需要添加两个变量。一个包含组合/ secret ,另一个包含猜测。

private String secret = "123";
private String guess = "";

这样您就可以随意组合;)

然后在您的 actionPerformed 方法中,您需要将最近的按钮点击添加到猜测中,根据 secret 进行检查,看看他们是否做出了正确的猜测。如果猜测的长度超过了 key 中的字符数,则需要重置猜测。

public void actionPerformed(ActionEvent evt) {
Object o = evt.getSource();
if (o instanceof JButton) {
JButton btn = (JButton) o;
guess += btn.getText();
if (guess.equals(secret)) {
JOptionPane.showMessageDialog(this, "Welcome Overloard Master");
dispose();
} else if (guess.length() >= 3) {
JOptionPane.showMessageDialog(this, "WRONG", "Wrong", JOptionPane.ERROR_MESSAGE);
guess = "";
}
}
}

关于java - 组合锁 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15469454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com