Class pair
JavaScript
x
public static class pair {
int x;
int y;
public void pair(int x, int y) {
this.x = x;
this.y = y;
}
}
main
function
What I want to do is to create an array of objects of class pair
and take input in the array of objects
JavaScript
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
pair[] p = new pair[2];
for (int i = 0; i < 2; i++) {
p[i].x = sc.nextInt(); // here I get the error is "Cannot assign field "x" because "p[i]" is null"
p[i].y = sc.nextInt();
}
}
Advertisement
Answer
JavaScript
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
pair[] p;
int x, y;
p = new pair[2];
for (int i = 0; i < p.length; i++) {
x = sc.nextInt();
y = sc.nextInt();
p[i] = new pair(x,y);
// Assign Object Instead of assigning to class members
}
for (int j = 0; j < p.length; j++) {
System.out.println(p[j].x + " "+ p[j].y);
}
}