1

好的,我有这个类库,它使用另一个名为 Book 的类。我想创建一个擦除数组库存中的对象书的方法,但我不知道如何声明该方法的返回值,我想返回对象库以在另一个类中使用它,我将在其中显示所有书在里面。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,在一个//switch

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

4 回答 4

2

如果void您不想返回任何东西(我假设这里就是这种情况),请使用。

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

于 2013-09-07T17:54:04.933 回答
0

添加一个构造函数 Library(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;
       }
   } 
 }  
}
于 2013-09-07T17:54:56.157 回答
0

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

public void eraseBook(int num){}

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

于 2013-09-07T19:14:21.347 回答
0

void如果您不想退回任何东西,请使用。

于 2013-09-07T18:56:51.590 回答