This question has already been answered:
- Variable for object 1 response
Hello! Please help me figure it out: I translate the task of working with structures from C ++ to Java, one thing doesn't work. As an analogue of the C ++ structure, I use the Book class, I create an array of Book [] arr with four elements — instances of the Book class; I set values for each through the constructor and try to output it to the console using a separate method. At the same time, the last filled-in element of the arr.length-time array is output to the console.
What is wrong, why the first three elements of the array are not displayed?
public class Main { public static int n = 4; public static void main(String[] args) { Book[] arr = new Book[n]; arr[0] = new Book (1, "Vinin", "Самоучитель по C++", 2001, 5 ); arr[1] = new Book (2, "Bikov", "Самоучитель по Java", 2002, 6 ); arr[2] = new Book (3, "Andreev", "Самоучитель по Python", 2003, 7 ); arr[3] = new Book (4, "Andreev", "Самоучитель по C#", 2004, 8); output(arr); } private static void output(Book a[]){ System.out.printf("%-4s%-1s%-8s%-1s%-27s%-1s%-8s%-1s%-8s%n", "id", "|", "Автор", "|", "Название", "|", "Год", "|", "Стеллаж|"); System.out.println("___________________________________________________________"); for (int i =0; i<a.length; i++) System.out.printf("%-4d%-1s%-8s%-1s%-27s%-1s%-8d%-1s%-7d%-1s%n", a[i].id, "|", a[i].author, "|", a[i].title, "|", a[i].year, "|", a[i].position, "|"); } } class Book{ public static int id; public static String author; public static String title; public static int year; public static int position; public Book(int id, String author, String title, int year, int position) { this.id = id; this.author = author; this.title = title; this.year = year; this.position = position; } } Результат: id |Автор |Название |Год |Стеллаж| ___________________________________________________________ 4 |Andreev |Самоучитель по C# |2004 |8 | 4 |Andreev |Самоучитель по C# |2004 |8 | 4 |Andreev |Самоучитель по C# |2004 |8 | 4 |Andreev |Самоучитель по C# |2004 |8 |
static- Alex Chermenin