I am writing a java code to add a student, remove a student and print the whole database of a class' grades. After running some times I have encountered 2 issues which I would like to find out where I am going wrong and what I can do to change my code.
1) Not sure why I am getting a null pointer exception error in my code, this is a code to help remove a student from a database and shift the students after into the position before. The issue is on this one line: if (student[l].equals(studenttoremove))
2) If I add a student in method newstudent, then remove a student in the method removestudent it will show up with nulls after printing the names to show which possible students to remove. How can I remove the nulls after it?
//studentgradedatabase
import java.util.Scanner;
public class studentgradedatabase
{
String newstudent;
int newgrade;
Scanner in = new Scanner(System.in);
String[]student = new String[10];
int[]grade = new int[10];
int numberofstudents = 0;
int matchstudent = 0;
int nullcounter = 0;
void newstudent(String a, int b)
{
newstudent = a.toUpperCase();
newgrade = b;
if (numberofstudents == 10 || numberofstudents > 10)
{
System.out.print("Maximum Number of Students exceeded, Please Delete a Student First");
}
else
{
student[numberofstudents] = newstudent;
grade[numberofstudents] = newgrade;
numberofstudents = numberofstudents+1;
}
}
void removestudent()
{
String studenttoremove;
for (int i=0;i<student.length-nullcounter;i++)
{
System.out.print(student[i] + " ");
}
System.out.println(" ");
System.out.println("Input the name of the student you want to remove: ");
studenttoremove = in.next().toUpperCase();
for (int l=0;l<student.length;l++)
{
if (student[l].equals(studenttoremove))
{
matchstudent = l;
}
else
{
System.out.print("Student name not found");
}
}
for (int y=matchstudent; y<student.length-1; y++)
{
student[y] = student[y+1];
grade[y] = grade[y+1];
}
for (int x=student.length-1; x<student.length;x++)
{
student[x] = null;
grade[x] = 0;
}
System.out.print("Removed Student");
}
void printdatabase()
{
for (int i=0;i<student.length;i++)
{
if (student[i] == null)
{
nullcounter = nullcounter+1;
}
}
for (int j=0;j<student.length-nullcounter;j++)
{
System.out.print(student[j] + " ");
}
System.out.println("");
for (int j=0;j<grade.length-nullcounter;j++)
{
System.out.print(grade[j] + " ");
}
}
}