如果我有一个在运行程序时更新的数组(比如我向玩家询问5个数字),请调用ClassA
,然后想要使用其他类保存它,称之为{{1从ClassB
导入数据,我该怎么做?
我能够创建一个全局变量并将该信息传递给ClassA
,但是如何将一个从不同方法获取参数的方法传递给该文件?
以下是我到目前为止的尝试:
ClassB
这是我要将此数组发送到的类:
class quiz
{
--- other code irrelavent to question ---
public static int[] scorearrayp1()
{
int[] scorep1 = new int[4]; // this creates the array that gets filled later
return new int[4];
}
public static void askQ(scorep1)
{
JOptionPane.showInputDialog("Some numbers");
// this method then fills the array depending on user input
// it is the values from here that I wish to save in classB
}
public static int[] passArray(int[] scorep1)
{
return scorep1; // this is from class A and takes the value from a method before
}
目前我被抛出两个错误
class saveScores
{
public static void main(String[] params) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("scores.txt"));
finalproject data = new finalproject();
int[] scores = data.passArray(int[] scorep1);
for (int i = 0; i < scores.length; i++)
{
outputStream.println(scores[i]);
}
outputStream.close();
System.exit(0);
}
}
我有想法将error:'.class' expected
int[] scores = data.passArray(int[] scorep1);
^
error:';' expected
int[] scores = data.passArray(int[] scorep1);
^
更改为passArray(int[] scorep1)
,但之后它只是告诉我无法找到该符号。
答案 0 :(得分:0)
更改
int[] scores = data.passArray(int[] scorep1);
到
int[] scores = data.passArray(scorep1);
但您仍需要声明scorep1
,例如:
int[] scorep1 = new int[]{1, 0, 0}
根据您编辑的问题(如果我理解的话),您的代码应如下所示:
int[] scores = quiz.passArray(quiz.scorearrayp1());
无论如何,请记住,班级名称应该始终为大写。
答案 1 :(得分:0)
您可以这样做:
class quiz{
int[] scorep1 = null;
public quiz()
{
scorep1 = new int[4]; // this creates the array that gets filled later
}
public static int[] askQ()
{
JOptionPane.showInputDialog("Some numbers");
// here call fills the array depending on user input
}
这样做:
int[] somearray = quiz.askQ();
int[] scores = data.passArray(somearray);
您应该像上面一样创建一个数组somearray
,以传递方法data.passArray(somearray);