所以我試圖將函數ActionPeformed的X的值傳遞給函數saveGame。然而,當它到達函數時,x的值變爲0. 順便說一下,我應該如何工作,程序將首先初始化每個玩家的值(有四個玩家),每個玩家都有一個X和Y值。當點擊保存按鈕時,它應該取每個玩家的X值並將其寫入一個文件中。將值從一個函數傳遞到Java中的另一個函數
這裏是我的代碼:
類的MainPage:
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();
}
}
}
級的球員:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Players{
private int x;
private int y;
.
.
.
public void setX(int x){
this.x = x; }
public int getX(){
return x; }
public void setY(int y){
this.y = y; }
public int getY(){
return y; }
}
請發佈[最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve) –
歡迎來到Stack Overflow!你已經在你的問題中發佈了很多代碼,這使得我們(以及未來的讀者)不清楚問題出在哪裏。請將您的問題代碼減少到10行或更少。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05 /如何調試的小程序/)。 –
這個問題不清楚。我在'actionPerfomed'中沒有看到'saveGame'的任何地方。你只是從不同的構造函數調用它。 –