如何声明方法返回值?

时间:2013-09-07 17:52:05

标签: java methods return-value

好的,我有这个类Libray使用另一个名为Book的类。 我想制作一个方法来删除数组库中的对象书,但我不知道如何 声明方法的返回值,我想返回对象libray以在另一个类中使用它,在那里我将显示其中的所有书籍。 用户在另一个类中给出的num变量,它表示要擦除的书的编号。阵列发明从0到9开始。

public class Library {

 private Book[] inventary;
 private int     booksquantity;

 public Library eraseBook(int num){
    for(int i=0 ; i<booksquantity ; i++){
         if(i == num-1){
            for(int j = i ; j<booksquantity ; j++){
                inventary[j] = inventary[j+1];}
         }          
   }return ***;
 }  
}

//在另一个类中,我会在//开关

中使用这个方法eraseBook
case 6: 
                    AppLibrary.cleanscreen();//Static method to erase the screen
                    System.out.println("What book do u wish to delete?");
                    String inventary = ghandi.generateInventory();//this makes the        //inventory to the user
                        if(inventary.equals("")){
                            System.out.println("No books available in the inventary");
                        }
                        else{
                            System.out.println(inventary);
                        }
                    int num = Integer.parseInt(s.nextLine());//here i read from the //keyboard the number of book the user wants to delete
//Here the object libary is caled "ghandi"
                    ghandi.eraseBook(num);//here i use the method
                    System.out.println("Book erase, please display inventary again");
                   s.nextLine();
                    break;

谢谢!

4 个答案:

答案 0 :(得分:2)

如果您不想返回任何内容,请使用void(我在此假设是这种情况)。

如果您想要返回您所在的对象(那么,您刚删除的当前库),请使用this关键字。

答案 1 :(得分:0)

添加构造函数库(Book [] inventary,int booksquantity)并在return方法中调用它。

public class Library {

 private Book[] inventary;
 private int     booksquantity;

 public Library(Book[] inventary, int booksquantity){
    this.inventary = inventary;
    this.booksquantity = booksquantity;
 }

 public Library eraseBook(int num){
    for(int i = 0; i<booksquantity ; i++){ 
       if((inventary[i] == inventary[num-1]) && (inventary[i+1] != null)){
           inventary[i+1]= inventary[i];
       } else if(inventary[i] == inventary[num-1]){
           inventary[i] = null;
       }
   } 
      return new Library(inventary, booksquantity);
 }  
}

如果您只是想要删除一本书而不是让整个课程不可变。

public class Library {

 private Book[] inventary;
 private int     booksquantity;

 public Library(Book[] inventary, int booksquantity){
    this.inventary = inventary;
    this.booksquantity = booksquantity;
 }

 public void eraseBook(int num){
    for(int i = 0; i<booksquantity ; i++){ 
       if((inventary[i] == inventary[num-1]) && (inventary[i+1] != null)){
           inventary[i+1]= inventary[i];
       } else if(inventary[i] == inventary[num-1]){
           inventary[i] = null;
       }
   } 
 }  
}

答案 2 :(得分:0)

如果您不想退回任何内容,请使用void

答案 3 :(得分:0)

您可以使用void作为方法签名:

public void eraseBook(int num){}

或者你可以在方法结束时返回null,但这不是一个好习惯。