i'm new to java programming. i have a problem with my code, i keep getting this error no matter what i try. so i have a main class and a Pair class (which has 2 member variables (private int a, private int b) the Pair class has it's setters and getters. i have been trying to create an array of Pair and initialize it, yet i keep getting this error: Exception in thread "main" java.lang.NullPointerException
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a puis b");
int x=0;
int y=0;
Pair p []= new Pair[6];
for (int i = 0; i < p.length; i++) {
x = sc.nextInt();
y = sc.nextInt();
p[i].setA(x);
p[i].setB(y);
}
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}
}
}
heres the Pair class:
public class Pair {
private int a = 0;
private int b = 0;
public Pair() {
this.b = 0;
this.a = 0;
}
public int getA() {
return a;
}
public void setA(int x) {
a = x;
}
public int getB() {
return b;
}
i need some help. thank you for your time :)
You are not initializing every member of your array, you need to use:
p[0] = new Pair();
And so on...
You can do this inside your for
loop:
for (int i = 0; i < p.length; i++) {
p[i] = new Pair();
... // more code
}