【问题标题】:Beginners Java Blue J returning a String in a method初学者 Java Blue J 在方法中返回一个字符串
【发布时间】:2023-04-02 23:23:02
【问题描述】:

您好,我希望我的方法通过 id 搜索一本书并返回标题,当我 printLn 时该方法工作正常,但我需要返回它而不是我收到错误:不兼容的类型意外返回值,该怎么办我需要去做 ?

编辑 我现在已将 void 更改为字符串,但我仍然收到错误:缺少返回值

提前致谢。

  public void returnByBookID(int enterBookId)
    {
          Iterator<Book> it = books.iterator();
          while(it.hasNext()) {
          Book books =  it.next();
          if(books.idNumber == (enterBookId)){

          return books.title ;
         }
            }
    }

【问题讨论】:

    标签: java methods return bluej


    【解决方案1】:

    你的方法返回类型是void,改成String返回书名。

    public String returnByBookID(int enterBookId){
    .....................
    ..............
    ........
    
     return books.title ;
    
    }
    

    还有return statementif condition里面,

    if(books.idNumber == (enterBookId)){
              return books.title ;
           }
    

    要么取空字符串并将书名分配给它并返回它,要么在最后返回 null 或 emty 字符串。

    public String returnByBookID(int enterBookId)
    String bookTitle = "";
        {
              Iterator<Book> it = books.iterator();
              while(it.hasNext()) {
              Book books =  it.next();
              if(books.idNumber == (enterBookId)){
                 bookTitle = books.title ;
             }
          }
    
       return bookTitle ;
      }
    

    【讨论】:

      【解决方案2】:

      将您的代码更改为以下内容:

      public String returnByBookID(int enterBookId) {
      
          Iterator<Book> it = books.iterator();
          while(it.hasNext()) {
              Book books =  it.next();
              if(books.idNumber == (enterBookId)){
      
                  return books.title ;
              }
          }
          return "ID not found";
      }
      

      【讨论】:

        猜你喜欢
        • 2016-01-11
        • 1970-01-01
        • 2015-03-15
        • 1970-01-01
        • 1970-01-01
        • 2017-07-04
        • 2012-07-04
        • 1970-01-01
        • 2019-09-01
        相关资源
        最近更新 更多