【发布时间】:2022-01-10 18:57:08
【问题描述】:
我目前正在开展一个涉及骰子游戏的项目,您可以在其中单击“掷骰”,骰子会生成数字并将其列在 JTextArea 上并添加到下面的总数中。
当用户得到 3 时,总数变为 0。
我的问题是,当按“滚动”时,总数不会每次都添加滚动的数字,而是显示当前滚动的数字。
JButton roll=new JButton("Roll");
roll.setBounds(900,750,75,30);
roll.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String command = e.getActionCommand();
if (command.equals ("Roll")){
int player1score = 0;
int player2score = 0;
int total = 0;
int total2 = 0;
Integer dice=(int)(Math.random()*6+1);
if (dice==1 || dice==2 || dice==4 || dice==5 || dice==6) {
area1.append(String.valueOf(dice + "\n"));
} else if(dice==3) {
dice = 0;
total = 0;
area1.setText(String.valueOf(total + "\n"));
totalbox1.setText(String.valueOf(total + "\n"));
}
total = total + dice;
totalbox1.setText(String.valueOf(total2));
}
}
});
【问题讨论】:
-
如果我理解正确:
total是一个应该累积滚动的变量。如果是,这应该超出 lambda 的范围。在您的代码中,total是局部变量,每次都初始化为 0。 -
请参阅minimal reproducible example 并相应地增强您的问题。含义:向我们展示您班级的相关部分。我猜你的
total信息有shadowing 的问题。看起来您的类中有一个具有该名称的 field,并且该方法中还有一个 local 变量。真的不清楚这里应该如何工作,