java - 如何返回一个对象?
问题描述
任务是=>
下一个单词的第一个字符必须与前一个单词的最后一个字符匹配。
这个词一定不是已经说过了。
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.
}
我没有给你所有的任务代码。我只是给,这正是你需要的。
解决方案
由于该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.
}
推荐阅读
- vba - 使用 TransferDatabase 将表从 oracle 导入外部访问数据库
- swift - Swift - 使用 SVG 和适当的比例 UIImage / UIBarButton
- php - Laravel Nova - 调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasManyThrough::save()
- reactjs - 用于上下文提供程序包装的类型道具
? - selenium - 如何将 chromedriver 添加到 PATH?
- python - 通过 MLE 收敛的 GEV
- java - MouseEvent - JSlider 没有更新最后点击的坐标
- javascript - 在变量中读取图片文件的内容
- python - python中__ALL__的对面(用于排除函数)
- python - 在张量上使用字典