我有一个很奇怪的问题,我有一个方法noOfPlayers,询问游戏中的玩家数量,一旦我有游戏中的玩家数量,我要求他们的每个名字反过来。一旦我得到了玩家的名字,就会创建一个框架,要求他们指定他们想要选择的计数器。当他们点击紫色宝石(出于测试目的)时,它应该在控制台中打印出玩家的名字,但for循环似乎不起作用。任何想法如何让环路正常工作?来自for循环的打印元素
public class setupPlayers extends JFrame implements ActionListener {
int intOfPlayers, purpleClick = 0, orangeClick = 0, iceClick = 0, greenClick = 0;
ArrayList<Player> arrayOfPlayers = new ArrayList<Player>();
JButton purpleGemBTN, greenGemBTN, iceCubeBTN, orangeGemBTN;
JFrame organisationPanel;
JPanel titleChoiceCounter, counterSelector;
ImageIcon finalCounter;
private static Dialog d;
public setupPlayers() {}
public void noOfPlayers() {
try {
String inputValue = JOptionPane.showInputDialog("Please input the number of players");
intOfPlayers = Integer.parseInt(inputValue);
if (intOfPlayers > 4) {
JOptionPane.showMessageDialog(null, "Only 1-4 can play!", "Error!", JOptionPane.ERROR_MESSAGE);
noOfPlayers();
intOfPlayers = 0;
}
for (int z = 0; z < intOfPlayers; z++) {
String playerName = JOptionPane.showInputDialog("Player " + (z + 1) + " please input your name");
chooseCounter();
arrayOfPlayers.add(new Player(playerName, (z + 1), null, 0));
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "You did not enter the number of players, please enter the number of players", "Error!", JOptionPane.ERROR_MESSAGE);
noOfPlayers();
}
}
public void chooseCounter() {
Frame window = new Frame();
ImageIcon purpleGemImg = new ImageIcon("C:\\Users\\Anonymous\\Documents\\pink.png");
ImageIcon greenGemImg = new ImageIcon("C:\\Users\\Anonymous\\Documents\\yellow.png");
ImageIcon orangeGemImg = new ImageIcon("C:\\Users\\Anonymous\\Documents\\brown.png");
ImageIcon iceCubeImg = new ImageIcon("C:\\Users\\Anonymous\\Documents\\white.png");
d = new Dialog(window, "Please select your counter", true);
d.setLayout(new GridLayout(2, 2));
d.setLocation(400, 300);
d.setSize(500, 500);
purpleGemBTN = new JButton("purple", purpleGemImg);
greenGemBTN = new JButton(greenGemImg);
orangeGemBTN = new JButton(orangeGemImg);
iceCubeBTN = new JButton(iceCubeImg);
purpleGemBTN.addActionListener(this);
greenGemBTN.addActionListener(this);
iceCubeBTN.addActionListener(this);
orangeGemBTN.addActionListener(this);
d.add(purpleGemBTN);
d.add(greenGemBTN);
d.add(orangeGemBTN);
d.add(iceCubeBTN);
d.setVisible(true);
}
public static void main(String[] args) {
setupPlayers spObj = new setupPlayers();
}
public void actionPerformed(ActionEvent e) {
JButton pressed = new JButton();
pressed = (JButton) e.getSource();
if (pressed.getText().equals("purple")) {
for (int z = 0; z < arrayOfPlayers.size() - 1; z = z) {
String currentPlayer = arrayOfPlayers.get(z).playerNme;
System.out.println(currentPlayer);
}
d.setVisible(false);
}
}
}
未来的参考:当你说“它似乎不工作”解释应该发生什么以及发生了什么。 –
我只注意到你递归调用'noOfPlayers();'我认为你会得到一些意想不到的结果。 –
我该如何解决这个问题,如果他们输入了一个无效的字符串数量的球员,不断询问球员的数量?那是我能想到做到的唯一方式。这是for循环不能正常工作的原因吗? – Blueaddiction