所以我试图将X的值从ActionPeformed函数传递给Function saveGame。但是,x到达函数时的值变为0。 顺便说一下,这是我应该如何工作,程序将首先初始化每个玩家的值(有四个玩家),每个玩家都有X和Y值。当点击“保存”按钮时,它应该取每个玩家的X值并将其写入文件中。
以下是我的代码:
Class MainPage:
username
班主任:
import java.awt.*;
import javax.swing.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.awt.event.*;
import java.util.Random;
import java.lang.Math.*;
import static java.util.logging.Logger.global;
public class MainPage extends JFrame implements ActionListener{
Random rand = new Random();
.
.
protected Players[] player = new Players[5];//declare array for players
int[] dtrump = new int[5];
public MainPage(boolean savegame)
{
saveGame();
}
public MainPage(){
.
.
.
for(int i=1;i<=4;i++){ //instantiate players
player[i] = new Players();
}
public void actionPerformed(ActionEvent e){
String ac = e.getActionCommand();
String num[] = ac.split("/");
int row = Integer.parseInt(num[0]);
int col = Integer.parseInt(num[1]);
boolean sucess = false;
boolean crash = false;
int x = player[turn].getX();
int y = player[turn].getY();
.
.
for(int i=1;i<5;i++) {
System.out.println(" - ");
System.out.println(player[i].getX());
dtrump[i] = player[i].getX();
System.out.println(dtrump[i]);
}
}
.
.
.
public void saveGame()
{
for(int i=1;i<5;i++) {
System.out.println(" - ");
//System.out.println(player[i].getX());
// dtrump[i] = player[i].getX();
System.out.println(dtrump[i]);
}
try {
//System.out.println(player[2].getX());
File save = new File("save.txt");
if (!save.exists()) {
save.createNewFile();
}
FileWriter savefile = new FileWriter(save);
for (int i = 1; i < 5; i++) {
System.out.println(dtrump[i]);
savefile.write(dtrump[i] + System.getProperty("line.separator"));
// savefile.write( pyerY[k]+ System.getProperty("line.separator"));
}
savefile.close();
//JOptionPane.showMessageDialog(null,"Eggs are not supposed to be green.");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
答案 0 :(得分:0)
这是我的怀疑。 protected Players[] player
是一个实例变量。由两个构造函数创建的对象(带有争论的对象和没有争论的对象)将拥有自己的副本(不是相同的实例变量)。从不同的对象访问似乎saveGame
和actionPerformed
。请尝试如下。
protected static Players [] player = new Players [5]; //为玩家声明数组
static int[] dtrump = new int[5];
答案 1 :(得分:0)
如果要将一个方法(即Java中引用的函数)中的值传递给另一个方法,您需要做的就是在方法的方法声明中,您希望传递X来执行以下操作:< / p>
public void saveGame(int aNumber){
the code you want to use X(passed and referred to as aNumber)...
}
然后在调用savegame方法时,你可以通过放置:
来传递X.saveGame(X);
这会将X的值传递给saveGame。 瞧!