【问题标题】:Passing an array as an argument in the update method of java observerable在 java observable 的更新方法中将数组作为参数传递
【发布时间】:2018-03-17 19:17:37
【问题描述】:

我正在开发一个简单的客户端-服务器游戏,其中客户端一旦成功登录,就会通知其观察者一个包含更新游戏所需的 25 个单词的数组。客户端正在发送正确的信息,但是 GUI 中的更新方法不是。更新方法如下。

public void update(Observable o, Object arg) {
    if (arg[0].equals("true1")) {
        for(int i = 1; i <26; i++]){
           String [i] words = args[i]; // sets the words to the args 
       }

       player = new PlayerView(client, words); // creates new playerview taking the client and an array of words

       this.setContentPane(player); // sets player view to content pane
    }
}

当我尝试这个时,我得到以下错误:

表达式的类型必须是数组类型,但解析为 Object

我尝试在 if 语句之前强制转换 args 但这似乎不起作用

【问题讨论】:

  • 定义“似乎不起作用”。

标签: java arguments observable updates


【解决方案1】:

这样做:

  • 检查arg实际上是一个字符串数组(String[])
  • 将其转换为字符串数组
  • words 声明为大小为 25 的数组(如果我正确理解您的算法)
  • 将索引 1 到 25 从 arg 数组复制到 words 数组

这应该可以工作

public void update(Observable o, Object arg) {
    // check that it is indeed an array
    if(arg instanceof String[]) {
        // cast it into an array
        String[] argArray = (String[]) arg;

        // make your words array
        String[] words = new String[25];
        if (argArray[0].equals("true1")) {
            for(int i=1; i<26; i++) {
                words[i-1] = argArray[i]; 
            }

            player = new PlayerView(client, words); // creates new playerview taking the client and an array of words

            this.setContentPane(player); // sets player view to content pane
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-25
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多