我正在编写一个java代码来添加学生,删除学生并打印一个班级成绩的整个数据库。运行一段时间后,我遇到了两个问题,我想知道我哪里出错了,以及我可以做些什么来改变我的代码。
1)不确定为什么我的代码中出现空指针异常错误,这是一个帮助从数据库中删除学生并将学生转移到之前的位置的代码。问题出在这一行:if(student [l] .equals(studenttoremove))
2)如果我在方法newstudent中添加学生,则删除方法中的学生removestudent在打印名称后将显示空值,以显示要删除的学生。如何删除之后的空值?
//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] + " ");
}
}
}