My method of addStudent is not working correctly Im trying t
My method of addStudent() is not working correctly. I\'m trying to put an Object of Students to an array. Everytime the user adds a new student it stores them in an array. But what\'s happening right now with my code is it just stores the newest student the user inputs. How can I correct this? thanks.
public class Project1 { static int size = 20; static Student[] students = new Student[size]; public static void main(String[] args) { while(true) { System.out.println(\"Student Database\"); System.out.println(\"================\"); System.out.println(\"Commands: \"); System.out.println(\"\\\"a\\\" - add a student\"); System.out.println(\"\\\"f\\\" - find a student\"); System.out.println(\"\\\"d\\\" - delete a student\"); System.out.println(\"\\\"p\\\" - print list\"); System.out.println(\"\\\"e\\\" - system exit\"); System.out.println(); Scanner scanner = new Scanner(System.in); String input = scanner.next(); switch (input) { case \"a\": addStudent(); break; case \"f\": findStudent(); break; case \"d\": deleteStudent(); break; case \"p\": printStudent(students); break; case \"e\": System.exit(0); break; }//switch }//while }//main public static void addStudent() { Scanner scan = new Scanner(System.in); System.out.println(\"Enter last name: \"); String lastname = scan.next(); System.out.println(\"Enter first name: \"); String firstname = scan.next(); System.out.println(\"Enter id no: \"); String id = scan.next(); for(int i=0; i<students.length; i++) { students[i] = new Student(lastname, firstname, id); } public static void printStudent(Student[] students) { for(Student s: students) { System.out.println(s); } } }
Solution
It is suggested to declare the number of students outside your main or use a larger MAX value and also make sure there is a variable which counts the actual number of array indices that are filled.
static int AR_MAX=20
static student[] students; //the same that is defined in the program//
static int nStudents; //this need to be added to keep a track of the number of entries//
students = new Student[AR_MAX]
nStudents=0;
//Then follow these lines of code to add a student//
students[nStudents]=new Student();
nStudents++;
The above code would limit the number of entries to 20 only.
