首页 > 解决方案 > 如何返回一个对象?

问题描述

任务是=>

  1. 下一个单词的第一个字符必须与前一个单词的最后一个字符匹配。

  2. 这个词一定不是已经说过了。

play; 将单词作为参数并检查它是否有效的方法(单词应遵循上述规则#1 和#2)。

如果有效,则将单词添加到数组中并返回数组。

如果它无效(任何一条规则都被破坏),它会返回“游戏结束”并将 设置game_over为 true。

该方法正在执行任务。谢谢@MCEmperor。 解决方法就是将方法从String[] 转为Object。这是错误的。

String []arr;
int counter;
char lastword;
boolean game_over;

public Shiritori () {
    this.arr= new String[1];
    this.counter=0;
    this.lastword=' ';
    this.game_over=false;

}
public String[] play(String item) {  //Turn here  public Object play(String item)
    if(controltheitem(item)) {
        game_over=true; 
        return "game over"; //It's string therefore giving error of course.
    }
    if(item.charAt(0)!=lastword&&counter>0) {
        game_over=true;
         return "game over"; //It's string therefore giving error of course.
    }
    arr[counter]=item;
    lastword=arr[counter].charAt(arr[counter].length()-1);
    counter++;
    expandCapacity();
    return arr;       //It returns words truly.
    
}

我没有给你所有的任务代码。我只是给,这正是你需要的。

标签: javamethods

解决方案


由于该play方法的返回类型是数组,您也想返回一个字符串。因此,您只需要将方法从String[]转换为Object。这样您也可以返回一个数组和一个字符串。由于更改为Object它将是genric类型:

public Object play(String item) {
    if(controltheitem(item)) {
        game_over=true; 
        return  "game over" ; //It's string therefore giving error of course.
    }
    if(item.charAt(0)!=lastword&&counter>0) {
        game_over=true;
         return "game over"; //It's string therefore giving error of course.
    }
    arr[counter]=item;
    lastword=arr[counter].charAt(arr[counter].length()-1);
    counter++;
    expandCapacity();
    return arr;       //It returns words truly.
    
}

推荐阅读