-1

Нужно положить в коллекцию объект, который имеет имя (name) и координаты (x, y).

Элементы, хранимые в коллекции, описываются в классе Product

public class Product {
String name;
Coordinates coordinates;

Product() { }

Product(String name, Coordinates coordinates) { this.name = name; this.coordinates = coordinates; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

@Override public String toString() { return "Product{" + "name='" + name + ''' + ", coordinates=" + coordinates.getX() +" "+ coordinates.getY()+ '}'; }

} Координаты x и y описываются в классе Coordinates

public class Coordinates {
int x;
int y;

Coordinates(int x, int y){ this.y=y; this.x = x; }

public int getX() { return x; }

public void setX(int x) { this.x = x; }

public int getY() { return y; }

public void setY(int y) { this.y = y; }

@Override public String toString() { return "Coordinates{" + "x=" + x + ", y=" + y + '}'; }

}` В классе Main осуществляется заполнение коллекции

public class Main {
public static  void main(String[] args){
    ArrayList<Product> list= new ArrayList<>();
    Product product = new Product();
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter name:");
    product.name = scanner.nextLine();
    System.out.println("Enter x:");
    product.coordinates.x = scanner.nextInt();
    System.out.println("Enter y:");
    product.coordinates.y = scanner.nextInt();
    list.add(product);
    System.out.println(product);

}

} Проблема заключается в том, что координаты добавить получается, но вывести их нет, выходит ошибка NullPointerException конкретно в этом фрагменте

public String toString() {
    return "Product{" +
            "name='" + name + '\'' +
            ", coordinates=" + coordinates.getX() +" "+
            coordinates.getY()+
            '}';
}

В чем заключается проблема ?

1 Answers1

1

Вы используете конструктор без параметров, в котором ничего не делается. И все поля у вас не проинициализированы.

product.coordinates окажется null после использования Product product = new Product();

mesfex
  • 307