首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操作数组以传递给不同的方法,然后类

操作数组以传递给不同的方法,然后类
EN

Stack Overflow用户
提问于 2015-12-08 16:12:20
回答 2查看 48关注 0票数 0

如果我有一个在运行程序时更新的数组(假设我向玩家要了5个数字),调用is ClassA,然后想用不同的类保存它,调用从ClassA导入数据的ClassB,我该怎么做呢?

我可以创建一个全局变量并将该信息传递给ClassB,但是如何将一个接受不同方法的参数的方法传递给这个文件呢?

以下是我到目前为止所尝试的:

代码语言:javascript
复制
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
   }

这是我想要将这个数组发送到的类:

代码语言:javascript
复制
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);
    }
} 

现在我被抛出了两个错误

代码语言:javascript
复制
error:'.class' expected
int[] scores = data.passArray(int[] scorep1);
                                    ^
error:';' expected
int[] scores = data.passArray(int[] scorep1);
                                           ^

我本想将passArray(int[] scorep1)更改为passArray(scorep1),但它只是告诉我找不到该符号。

EN

回答 2

Stack Overflow用户

发布于 2015-12-08 16:16:24

变化

代码语言:javascript
复制
int[] scores = data.passArray(int[] scorep1);

代码语言:javascript
复制
int[] scores = data.passArray(scorep1);

但是您仍然需要声明scorep1,例如:

代码语言:javascript
复制
int[] scorep1 = new int[]{1, 0, 0}

根据您编辑的问题(如果我理解正确的话),您的代码应该如下所示:

代码语言:javascript
复制
int[] scores = quiz.passArray(quiz.scorearrayp1());

无论如何,请记住类名应该总是大写的。

票数 0
EN

Stack Overflow用户

发布于 2015-12-08 16:16:56

你可以这样做:

代码语言:javascript
复制
 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
  }

然后这样做:

代码语言:javascript
复制
  int[] somearray = quiz.askQ();
  int[] scores = data.passArray(somearray);

您应该创建一个类似于上面的数组somearray来传递给data.passArray(somearray);方法

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34150932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档