Java 类型字符串的方法未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22443449/
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-08-13 15:45:16  来源:igfitidea点击:

the method is undefined for the type string

javastring

提问by user1347096

why would I have "the method is undefined for the type string" in java with this statement:

为什么我会在 java 中使用以下语句“未定义类型字符串的方法”:

if(book.getTitle().getAuthor().getAward()){..}

the error is for getAward()

错误是针对 getAward()

when I have defined a class Author as this:

当我定义一个类 Author 时:

class Author {

private String name;
private boolean award;
public Author(String n, boolean p){
    name=n;
    award=p;
}

public String getName(){return name;}
public boolean getAward(){return award;}

} May the error come from another definition (other than Author?)

错误可能来自另一个定义(除了作者?)

采纳答案by Stephen C

actually get Author is in another class and returns a string. getTitle is from a third class and returns string as well. Book is from a fourth class.

实际上 get Author 在另一个类中并返回一个字符串。getTitle 来自第三个类,也返回字符串。书是第四班的。

Then the answer is obvious.

那么答案就显而易见了。

You are attempting to call getAuthor()on the result of calling getTitle(). But the result of getTitle()is a String... and Stringdoesn't have a getAuthor()method.

您正在尝试调用调用getAuthor()的结果getTitle()。但结果getTitle()String... 并且String没有getAuthor()方法。

And that is exactly what the compilation error is telling you.

这正是编译错误告诉你的。



In fact, you probably should write:

事实上,你可能应该写:

if(book.getAuthor().getAward()){..}

then change getAuthor()to return the Auteurobject ... rather than the author's name.

然后更改getAuthor()以返回Auteur对象...而不是作者的姓名。

A book (Oevre) has an author, but a title (String) does not.

一本书 (Oevre) 有作者,但书名 (String) 没有。

回答by RMachnik

change your getAuthor()method implementation to that

将您的getAuthor()方法实现更改为

public Author getAuthor(){
   return new Author(); // or some author that is set in your object
}

And on that you can performe another method. if(book.getTitle().getAuthor().getAward())if Author class have method getAward

并且您可以执行另一种方法。 if(book.getTitle().getAuthor().getAward())如果 Author 类有方法getAward

public class Author{
  public boolean getAward(){ // implementation
  }
}

回答by Sajan Chandran

You need to change your getAuthormethod to

你需要改变你的getAuthor方法

public Author getAuthor(){
  return author;
}

and if you want the authorsaward, then u should invoke

如果你想要authorsaward,那么你应该调用

book.getAuthor().getAward()

book.getAuthor().getAward()