简体   繁体   English

如何使用toString()-Method获得每个对象数量增加的输出? 爪哇

[英]How can I get an Output with an increasing number per object with the toString()-Method? Java

I'm using the toString()-Method to get the proper output from my ArrayList. 我正在使用toString()方法从ArrayList获取正确的输出。

But I'm still not able to get an Output where the number increases per object. 但是我仍然无法获得一个输出,其中每个对象的数量增加。

The current code I have written is as follows: 我编写的当前代码如下:

public class Book {  

    @Override
         public String toString() {

              StringBuilder result = new StringBuilder();

              int i = 1;

              result.append("\n\n-Book "+ i++ +": ");
              result.append("\nTitel: " + this.Titel + "§ ");
              result.append("\nAuthor: " + this.Autor + "§ ");

              return result.toString();
         }

by inserting ' i++ ' I'm trying to get an output, 通过插入“ i++ ”,我试图获得输出,

where the number increases for each object from the public class Book(); public class Book();每个对象的数量增加public class Book();

Current Output: 电流输出:

-Buch **1**:  
Titel: Hunger Games§ 
Author: Suzanne Collins§ ,

-Buch **1**:   
Titel: Twilight§ 
Author: Stephanie Meyer§ ,

-Buch **1**: 
Titel: Pride and Prejudice§ 
Author: Jane Austen§ ,

Output I'm trying to get: 我试图得到的输出:

-Buch **1**:  
Titel: Hunger Games§ 
Author: Suzanne Collins§ ,

-Buch **2**:   
Titel: Twilight§ 
Author: Stephanie Meyer§ ,

-Buch **3**: 
Titel: Pride and Prejudice§ 
Author: Jane Austen§ ,

What you need is to set your i variable as static and class field. 您需要将i变量设置为static和class字段。

public class Book {  

    private static int i = 1;


    @Override
         public String toString() {

              StringBuilder result = new StringBuilder();


              result.append("\n\n-Book "+ i++ +": ");
              result.append("\nTitel: " + this.Titel + "§ ");
              result.append("\nAuthor: " + this.Autor + "§ ");

              return result.toString();
         }

Exactly, you can use a static variable. 确实,您可以使用静态变量。 But instead of increasing it inside the toString() Method id rather increase it in the constructor since your question suggests you want to count the number of objects, not the number of times the toString() method was called on one of your object instances. 但是不要在toString()方法id内增加它,而是在构造函数中增加它,因为您的问题建议您要计算对象的数量,而不是在您的一个对象实例上调用toString()方法的次数。

public class Book {  

private static int i = 0;

public Book(){
   i++;
}

@Override
     public String toString() {

          StringBuilder result = new StringBuilder();


          result.append("\n\n-Buch"+ i +": ");
          result.append("\nTitel: " + this.Titel + "§ ");
          result.append("\nAuthor: " + this.Autor + "§ ");

          return result.toString();
     }
}

Edit: Below comment is correct, this will always print out how many books have been created the time you call the toString() method of any Book object. 编辑:下面的注释是正确的,在您调用任何Book对象的toString()方法时,这将始终打印出已创建了多少本书。

Here is a second Version, you now have one variable per object instance identifing the books number according the time it was created and the same static variable from above, look at the sample output. 这是第二个版本,现在每个对象实例都有一个变量,可根据创建时间来标识帐簿编号,并从上方查看相同的静态变量,请查看示例输出。

public class Book {

private static int i = 0;
private int i2;

public Book() {
    i2 = i;
    i++;
    // or place 'i2 = i;' here if you want to start with "Book 1 of..."
}

@Override
public String toString() {

    StringBuilder result = new StringBuilder();

    result.append("Book " + i2 + " of " + i + " books in total");

    return result.toString();
}
}

Sample Call: 样品电话:

public class SampleCall{

public static void main(String[] args) {

    Book b = new Book();
    Book b1 = new Book();
    Book b2 = new Book();
    Book b3 = new Book();

    System.out.println(b1);
          System.out.println(b1);

}    
}

Sample Output: 样本输出:

Book 0 of 4 books in total
Book 1 of 4 books in total

Since you just started using Java consider a solution where you are setting the number for each Book instance by yourself just for completion: 由于您刚开始使用Java,请考虑一个解决方案,在该解决方案中,您自己为完成每个Book实例设置编号:

public class Book {

private static int i = 0;
private int bookNumber;

public Book(int bookNumber) {
    i++;
    /* this.bookNumber means "the variable of the currently in creation book object instance)
     * you only need it if its not clear because there is a local variable with the same name 
     */
    this.bookNumber = bookNumber;
}

// a second (default) constructor in case you want to create book objects and dont yet know the number of it
// after creation you can use the get/set values to access the variable from "outside"
public Book(){
    i++;
}

@Override
public String toString() {

    StringBuilder result = new StringBuilder();

    // Here you dont need this because there is no local variable bookNumber
    // You can however always use it when referencing such object variables 
    result.append("Book " + bookNumber + " of " + i + " books in total");

    return result.toString();
}

public int getBookNumber(){
    return bookNumber;
}

public void setBookNumber(int bookNumber){
    this.bookNumber = bookNumber;
}
}

Sample Call: 样品电话:

public class SumeMain {

public static void main(String[] args) {

    Book b = new Book(1);
    Book b1 = new Book(2);
    Book b2 = new Book();

    System.out.println(b);
    System.out.println(b1);

    //Note below book not yet has a number:
    System.out.println("Forgotten book: "+b2);

    //But you can set it from "outside" (here)
    b2.setBookNumber(3);

    System.out.println(b2);

    //Also note you now took controll of those numbers so two books can have the same number:
    b2.setBookNumber(2);

    System.out.println("Duplicate book number: "+b2);
}


}

Sample Output: 样本输出:

Book 1 of 3 books in total
Book 2 of 3 books in total
Forgotten book: Book 0 of 3 books in total
Book 3 of 3 books in total
Duplicate book number: Book 2 of 3 books in total

By such examples i think youre on the best way to learn the language basics, keep up and have fun :) 通过这样的例子,我认为您是学习语言基础,保持学习和娱乐的最佳方法:)

You are calling toString() method on an encapsulated Book object. 您正在封装的Book对象上调用toString()方法。 It has no knowledge of other Book's in ArrayList. 它不了解ArrayList中的其他Book。

Try removing those lines from toString() method: 尝试从toString()方法中删除这些行:

int i = 1;
result.append("\n\n-Book "+ i++ +": ");

And iterate over collection like this: 然后像这样遍历集合:

List<Book> books = ...
for(int i = 0; i < books.size(); i++){
    System.out.println("\n\n-Book "+ (i + 1) +": ");
    System.out.println(books.get(i));
}

Strange that you know how to use toString() and StringBuilder, but experience problems in iterating collections. 奇怪的是,您知道如何使用toString()和StringBuilder,但是在迭代集合时遇到了问题。 Try going back to basic programming techniques. 尝试回到基本的编程技术。

Also, a lot of answers recommend using a static field. 另外,很多答案建议使用静态字段。 Don't go with that approach. 不要采用这种方法。 Static fields are not good for this. 静态字段对此不利。 It won't work in case you have to iterate the collection of books twice. 万一您必须对书库进行两次迭代,它将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM