java 获取“该方法未定义为字符串类型”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27026482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:05:44  来源:igfitidea点击:

Getting "The method is undefined for the type String"

javasyntax

提问by Paecko

I am a newbie following the book 'Head First Java', and following one of the projects in the book. I ran into an error on the last line of the main method - "The method checkYourself(String) is undefined for the type String"

我是一个新手,关注“Head First Java”一书,并关注本书中的一个项目。我在 main 方法的最后一行遇到了一个错误——“方法 checkYourself(String) 未定义为 String 类型”

class dotcom{
    int [] Locationcells;
    int hits = 0;

public String checkYourself(String guess){
    int guess1 = Integer.parseInt(guess);
    String result = "miss";

    for(int cell : Locationcells){
        if(guess1 == cell){
            result = "hit";
            hits = hits + 1;
            break;
        }
    }
    if (hits == Locationcells.length){
        result = "kill";



    }
    System.out.println(result);
    return result;


}
public void setCellLocations(int []locs){
    Locationcells = locs;

}
}




public class SimpleDotComGame {
    public static void main(String[] args) {
        dotcom dotMan = new dotcom();
        int locations [] = {3,4,5};
        dotMan.setCellLocations(locations);


        String userguess = "2";
        String result = userguess.checkYourself(userguess);



}
}

回答by Cristian Meneses

You are calling a method checkYourselffor the String value

您正在调用checkYourselfString 值的方法

userguess.checkYourself(userguess);

... which doesn't exists for the String class.

... String 类不存在。

It should be

它应该是

dotMan.checkYourself(userguess);

回答by Daniel Rodriguez

You would like to do

你想做

String result = dotman.checkYourself(userguess);

instead of

代替

String result = userguess.checkYourself(userguess);

The error message means that checkYourselfis not a method in the Stringclass.

错误消息意味着这checkYourself不是String类中的方法。

回答by gashu

result = dotMan.checkYourself(userguess)

结果 = dotMan.checkYourself(userguess)