I have this code in java: public static int addRecord(Scanner input, PrintWriter
ID: 3744160 • Letter: I
Question
I have this code in java:
public static int addRecord(Scanner input, PrintWriter output, Student[] students) {
int id = input.nextInt();
String fname = input.next();
String lname = input.next();
int g1 = input.nextInt();
int g2 = input.nextInt();
int g3 = input.nextInt();
int index = -1;
Student s = new Student(fname, lname, id, g1, g2, g3, (((g2 * (0.3)) + (g3 * (0.4)) + (g1 * (0.3)))));
// save new student into array
students[0] = s;
output.println("Command: ADDRECORD");
output.println(fname + " " + lname + " (ID# " + id + ")" + " has been added to the FSC Grade Book");
output.println(" His final grade is " + s.getFinalGrade());
if (Student.getNumStudents() == 0) {
students[0] = s;
return 0; // once we insert a, stop looping
}
for (int y = 0; y < Student.getNumStudents(); y++) {
if (id < students[y].getID()) {
index = y;
Student.increaseStudents();
System.out.println(Student.getNumStudents());
}
}
if (index != -1) {
for (int i = Student.getNumStudents() - 1; i >= index; i--) {
students[i + 1] = students[i];
}
Student.increaseStudents();
students[index] = s;
} else {
Student.increaseStudents();
index = Student.getNumStudents();
if (index < Student.getNumStudents()) {
students[index] = s;
} else {
System.out.println("ERROR: Adding student not possible, book reached max size");
return -1;
}
}
return index;
}
But it wont increase the number of students for some reason? Why and how do i fix this?
Explanation / Answer
If you have any doubts, please give me comment...
public static int addRecord(Scanner input, PrintWriter output,
Student[] students) {
int id = input.nextInt();
String fname = input.next();
String lname = input.next();
int g1 = input.nextInt();
int g2 = input.nextInt();
int g3 = input.nextInt();
int index = -1;
Student s = new Student(fname, lname, id, g1, g2, g3,
(((g2 * (0.3)) + (g3 * (0.4)) + (g1 * (0.3)))));
output.println("Command: ADDRECORD");
output.println(fname + " " + lname + " (ID# " + id + ")"
+ " has been added to the FSC Grade Book");
output.println(" His final grade is " +
(((g2 * (0.3)) + (g3 * (0.4)) + (g1 * (0.3)))) + "("
+ ")");
for (int i = 0; i < Student.getNumStudents();i++) {
for (int y = 0; y < Student.getNumStudents(); y++)
if (id < students[y].getID()) {
index = y;
}
}
if (index != -1) {
for (int i = Student.getNumStudents() - 1; i > index; i--) {
students[i + 1] = students[i];
}
students[index] = s;
} else {
index = Student.getNumStudents();
if(index<Student.length){
students[index] = s;
Student.increaseStudents();
}
else{
System.out.println("Adding student not possible, it reached to max size");
return -1;
}
}
return index;
}