如果String确认输入不是“ Y”或“ y”以外的任何内容,我希望Play()再次运行。当我按下战争按钮时,它将显示输入对话框,如果我输入“ N”,它将按预期运行。但是,如果我按任意按钮并在同一程序运行中再次输入“ N”,它将要求确认2次。如果我再次执行此操作,它将要求确认4次,然后以2的幂继续这种模式。是什么原因引起的,并且有更好的方法来确认用户的选择吗?
在尝试再次运行play()之前,我曾尝试在else {}中将String确认设置为等于“”,这没有用,而且我也没想到会起作用。但是除此之外,我不知道。
公共类主要{
public static void main(String[] args) {
GUI heroSelect = new GUI(450, 200, "Inscription", new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel heroLabel = new JLabel("Choose your class, hero.");
heroLabel.setFont(new Font("Serif", Font.PLAIN, 22));
c.gridx = 1;
c.gridy = 0;
c.weightx = .5;
c.weighty = .5;
heroSelect.add(heroLabel, c);
JButton war = new JButton("Warrior");
c.gridx = 0;
c.gridy = 2;
heroSelect.add(war, c);
JButton mage = new JButton("Mage");
c.gridx = 1;
c.gridy = 2;
heroSelect.add(mage, c);
JButton rog = new JButton("Rogue");
c.gridx = 2;
c.gridy = 2;
heroSelect.add(rog, c);
play(war, mage, rog);
}
public static void play(JButton war, JButton mage, JButton rog) {
war.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String confirm = JOptionPane.showInputDialog(null, "The warrior "
+ "is a strong, hard-hitting class. It relies on raw "
+ "damage and heals through offensive abilities.\n "
+ "However, the warior does not possess any direct "
+ "healing or spells. Are you sure you want to choose "
+ "this class? Y/N");
if(confirm.equalsIgnoreCase("Y")) {
//TBD
}
else {
play(war, mage, rog);
}
}
});
mage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String confirm = JOptionPane.showInputDialog(null, "");//ADD DESCRIP
if(confirm.equalsIgnoreCase("Y")) {
}
else {
play(war, mage, rog);
}
}
});
rog.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String confirm = JOptionPane.showInputDialog(null, "");//ADD DESCRIP
if(confirm.equalsIgnoreCase("Y")) {
}
else {
play(war, mage, rog);
}
}
});
}
}
当用户输入“ N”或“ n”时,showInputDialog应该关闭,并且应该重新运行play()以允许用户查看其他类的描述并最终选择一个。相反,为此输入“ N”或“ Y”或“ y”以外的任何内容会导致出现多个showInputDialog背靠背提示。
答案 0 :(得分:2)
通过在自身内部调用play()方法来执行的操作称为递归,每次调用时,都会向按钮添加更多的EventListeners。
我认为代替if-else的do-while循环会反复检查输入,
// Get the path to the resource file
var configurationFileURL = NSBundle.MainBundle.PathForResource("client", "conf");
// Make sure the file exists
if (configurationFileURL != null)
{
// load the text content of the file into a string variable declared elsewhere
configurationFileContent = File.ReadAllText(configurationFileURL);
}
答案 1 :(得分:1)
您在Play方法中创建的侦听器中调用Play方法。每当您为每个英雄做新的听众时。 还请阅读有关OOP(在Java中使用对象比对初学者使用GUI更为重要:))
作为关于更好的方法的问题,我真的鼓励您熟悉模式。 仅仅收集输入是非常简单的事情,例如,您可以选择多种选择,例如循环切换案例。