I'm trying to make a program that takes input from the user for how many students they have in their class and their names/grades and calculate average and letter grades. I'm trying to get better with For Loops and Arrays and this is what I chose to do. The only problem is when the init() method is called to make the window. The class is extending JFrame
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class GradesGUI_2 extends JFrame {
static Scanner s = new Scanner(System.in);
static int num;
public static void main(String[] args) {
System.out.println("How many students are in your class?");
num = s.nextInt();
GradesGUI_2 window = new GradesGUI_2("Title");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//-------------------------------------------------
static JPanel p;
JTextField[] name = new JTextField[num], grade = new JTextField[num];
JLabel[] nlabel = new JLabel[num], glabel = new JLabel[num];
int height = 50;
//-------------------------------------------------
GradesGUI_2(String title) {
super(title);
this.init();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
//-------------------------------------------------
void init() {
//Create JLabel/JTextField
for(int i = 0; i < num; i++) {
nlabel[i] = new JLabel("Name " + i);
glabel[i] = new JLabel("Grade " + i);
name[i] = new JTextField(10);
grade[i] = new JTextField(1);
height += 25;
}
for(int i = 0; i < num; i++) {
p.add(nlabel[i]);
p.add(glabel[i]);
p.add(name[i]);
p.add(grade[i]);
}
this.setSize(350, height);
this.add(p);
}
}
What the console displays:
How many students are in your class?
7
Exception in thread "main" java.lang.NullPointerException
at GradesGUI_2.init(GradesGUI_2.java:59)
at GradesGUI_2.<init>(GradesGUI_2.java:40)
at GradesGUI_2.main(GradesGUI_2.java:20)
The error happens when the components are added to the panel. Please answer. Thank you!