我想创建一个简单的程序,它有一个“玩家”和一个“怪物”并绘制随机数字以降低健康。然后我希望它在文本区域打印。除了FightTheMonster方法,我的变量怪物和玩家正在被重置为0。 (对于草率代码,提前抱歉)。当我使用playerDied或monsterDied方法打印怪物或玩家时,无论如何它们都打印为0,这也发生在主要方法中。变量在方法中被重置
import java.util.Random;
import java.awt.*;
import javax.swing.*;
public class Main extends JPanel {
JTextArea textArea;
static final String NEWLINE = System.getProperty("line.separator");
public static int player;
public static int monster;
private static void CreateAndShowGui() {
JFrame frame = new JFrame("Monster Fight");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Main();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void FightTheMonster() {
boolean loop = true;
Main.player=10;
Main.monster=10;
while (loop == true) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
Random monsterroll = new Random();
int m = monsterroll.nextInt(3) + 1;
player = player - n;
monster = monster - m;
System.out.println("player health " + player + " monsterhealth " + monster);
if(player <= 0) {
loop = false;
System.out.println("Player Died");
}
if(monster <= 0) {
loop = false;
System.out.println("Monster Died");
}
}
}
public void monsterDied(int monster) {
Main.monster = Main.monster;
System.out.println("monster health in void" + monster);
if(monster <= 0) {
textArea.append("Monster Died");
System.out.println("Monster Died in void");
}
}
public void playerDied(int player) {
if(player <= 0) {
textArea.append("Player Died");
System.out.println("Player Died in void");
}
}
public Main() {
super(new GridLayout(0,1));
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 75));
add(scrollPane);
}
public static void main(String[] args) {
Main.monster = Main.monster;
System.out.println("Monster Health in Main Method " + monster);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CreateAndShowGui();
FightTheMonster();
}
});
Main juice = new Main();
juice.playerDied(player);
juice.monsterDied(Main.monster);
}
}
哎呀,没有注意到我错过了,谢谢! – MangoesRAwesome