This question has already been answered:

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 | 

Reported as a duplicate by Anton Shchyrov , Spirit of the Community Jan 18 '18 at 16:33 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • read about the keyword static - Alex Chermenin
  • 2
    Hey, we need a canonical question-answer on statics to close such questions :) - Alex Chermenin
  • @AlexChermenin Write :) An hour ago there was the same question - Anton Shchyrov
  • one
    @AlexChermenin I found a clear answer. You can cling to it all - Anton Shchyrov

1 answer 1

Remove static from field declarations. Must be so

 class Book{ public int id; public String author; public String title; public int year; public int position; 
  • Thank you!)) Understand the mistake) - Aleksandr
  • @Aleksandr If my answer solved your problem, mark it as correct - Anton Shchyrov
  • I'm waiting - a temporary restriction) - Aleksandr