package student;
import javax.swing.JOptionPane;
public class Student
{
private Name name;
String idNUM, course;
public Student(Name n, String idNum){
this.name = n;
this.idNUM = idNum;
}
public Name getName(){
return name;
}
public String getId(){
return idNUM;
}
}
package student;
public class StudentCourse
{
Student studInfo, studentInfo;
String studentCourses, studentCourse;
StudentCourse(String sc)
{
studentCourses = sc;
}
public String getCourses(){
return studentCourses;
}
}
package student;
public class StudentAccounts
{
private Student stud;
private String addedClass;
String courses;
public StudentAccounts (Student s, String course)
{
stud = s;
courses = course;
}
public Student getStudent()
{
return stud;
}
public void insertClass(String cla)
{
courses = cla;
}
public String getCourses()
{
return courses;
}
}
Sorry for posting a lot of code. But right here is where the problem is. in the Database class below. The method "void addCourses(StudentCourse e)". When running the test class. It crashes right after entering a course name, it won't store it like the student name. Im a little new with programming cohesively. Can someone please explain what I am missing?
package student;
import java.util.ArrayList;
public class DataBase
{
ArrayList <StudentAccounts> list;
ArrayList <StudentCourse> courseList;
StudentAccounts sa ;
StudentCourse sc;
int index;
boolean found = false;
DataBase()
{
list = new ArrayList<> ();
}
ArrayList getList()
{
return list;
}
ArrayList getCourseList()
{
return courseList;
}
StudentCourse getCourse(){
return sc;
}
StudentAccounts getAccount()
{
return sa;
}
StudentAccounts delete (int d)
{
return list.remove(d);
}
boolean inList() //Looks in the ArrayList
{
return found;
}
boolean isEmpty()
{
return list.isEmpty();
}
int getIndex()
{
return index;
}
int getSize() // return the amount of strings in the Array
{
return list.size();
}
void add(StudentAccounts s)
{
list.add(s);
}
void addCourse(StudentCourse e)
{
courseList.addCourse(e);
}
void search(String key)
{
found = false;
int i = 0;
while (!found && i < list.size() )
{
StudentAccounts sl = list.get(i);
if(sl.getStudent().getId().equalsIgnoreCase(key))
{
sa =sl;
found = true;
index = i;
}
else
i++;
}
}
}
You have not initialized your courseList variable. You have initialized only the one list variable in the constructor Database. When you add a course, the addCourse() method will throw a null pointer exception.
Add the following line in your Database constructor:
courseList = new ArrayList<>();
Also, the line courseList.addCourse(e) should be a compilation error (so silly of me). courseList is an object of type ArrayList. ArrayList class does not have a method called addCourse(Studentcourse e). It only has a method add() which will take an object of type StudentCourse in your case. So you will see a cannot find symbol error.
Change that line to:
courseList.add(e);
Related
I've created the class Course which contains the array students. This array contains student names which are in string form.
My new goal is to convert from an Array to an ArrayList. I'm not really sure how to go about this. I've read up on ArrayList and I believe it's resize-able which I think would work well in this case given the fact that the number of students might change constantly with my dropSutdent and addStudent method as opposed to setting an array size to 100, but only having 20 students.
I'd really appreciate and explanations/suggestions of how exactly to change to an ArrayList instead of an Array.
Note I apologize for any mistakes or if I left something unclear. This is my first question on StackOverflow and I know you guys are pretty strict on question asking, so I apologize in advance.*
class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
int add = numberOfStudents - students.length; //Create integer to find how many slots we need
if (numberOfStudents > students.length) { //if # of students is bigger then size of array,
String[] array = new String[students.length + add]; //then we add slots to the array.
System.arraycopy(students, 0, array, 0, students.length); //copy array
students = array;
}
students[numberOfStudents++] = student; //add student.
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
for (int i = 0; i < students.length; i++) {
if (student == (students[i])) { //If student matches the student we want to remove.
numberOfStudents--; //remove student
while (i < numberOfStudents) {
students[i] = students[i+1];
i++;
}
}
}
}
public void clear() {
students = new String[1]; //set size to 1
numberOfStudents--; //remove all students
}
}
List handles resizing internally, which means you can remove most of the boilerplate by using it instead of an array.
class Course {
private String courseName;
private List<String> students = new ArrayList<>();
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students.add(student);
}
public List<String> getStudents() {
return students;
}
public int getNumberOfStudents() {
return students.size();
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
while (students.remove(student));
}
public void clear() {
students.clear();
}
}
ArrayLists are really usefull, but if you need more options, you can always create a class that works like list and implement all the methods as you wish.
Example for students:
public class studentList{
int size;
Student [] list;
public studentList()
{
size = 0;
list = new Student[size];
}
public studentList(int size)
{
this.size = size;
list = new Student[size];
}
public void add(Student s)
{
}
public void remove(Student s)
{
}
public void sort()
{
}
}
You can implement as you wish.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
so when i try to run my Group class, it tells me that the content of the student array is null and i cant find where specifically (been spending the last 4 hours trying to figured it out).if you have any questions regarding of classes, dont hesitate to ask.
thanks in advance for all of your answers.
Group class
public class Group {
private Student studentArray[];
private int nbOfStudent;
public Group() {
studentArray[]= new Student[24];
}
public void add( Student stud){
studentArray[nbOfStudent]=stud;
nbOfStudent++;
}
public String toString(){
String msg="";
for(int i=0;i<studentArray.length;i++){
msg+=tabStudent[i]+" ";
}
return msg;
}
public Student getStudentArray(int i) {
return studentArray[i];
}
public Student[] getstudentArray(){
return studentArray;
}
public void setStudentArray[](Student[] studentArray) {
this.studentArray= studentArray;
}
public int getNbOfStudent() {
return nbOfStudent;
}
public void setNbOfStudent(int student) {
this.nbOfStudent = student;
}
public int search(String code){
return UtilsTabs.search(studentArray, code,this.nbOfStudent);
}
public void sort(){
UtilsTabs.sort(studentArray, nbOfStudent);
}
}
UtilsTabs class
public static void sort(Student[] array, int nbOfStud){
Student temp=null;
int minIndex=0;
for(int i=0;i<array.length-1;i++){
minIndex=i;
for(int j=i+1;j<nbOfStud;j++){
int comparedValue = tab[j].compareTo(tab[minIndex]);
if( comparedValue< 0){
minIndex=j;
}
}
temp=tab[i];
array[i]=array[minIndex];
array[minIndex]=temp;
}
}
public static int search(Student array[],String code,int nbofStud){
int pos=-1;
for(int i=0;i<tarray.length;i++){
if(tab[i].getCode().equalsIgnoreCase(code));
pos=i;
}
return pos;
}
Student class
public class Student {
private String code;
private String name;
private Grades evaluation;
public Student(String code, String name, String eval) {
this.code = code;
this.nom = nom;
this.evaluation=new Grades(eval);
}
public Message message(){
if(this.evaluation.gradeAverage()<60)
return Message.FAILED;
else
return Message.SUCCESS;
}
public boolean equals(Student other){
boolean res=this.code.equals(other.code);
return res;
}
public int compareTo(Student other){
int res= this.code.compareTo(other.code);
return res;
}
}
test of class group
Group gr = new Group();
Student stud2 = new Student("26161234", "Marc", "65 81 58 100 79");
gr.add(stud2);
Student stud=new Student("24910003", "Pierre", "45 59 36 66");
gr.add(stud);
//show group of student
System.out.println("Group of students:\n" + gr.toString());
this is what the console shows me
result of test of Group class
Your group.toString is using tabStudent which i cant see getting initialised or used anywhere else
I have a Contact class that basically just holds information of a contact. We store the contact object in an array.
I had to write the array into a text file, and I knew how to do that, but now I must read that file and store the objects back into an array, and I'm stuck!
Note, ContactList Below also uses class Contact, which just basically has get/set methods.
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
public class ContactList{
int ptr = -1;
Contact[] list;
int contactLength;
public ContactList(){//second constructor needed
list=new Contact[20];
contactLength=20;
for(int i =0;i<20;i++){
list[i]=null;
}
}
public ContactList(int length){//second constructor needed
list=new Contact[length];
contactLength=length;
for(int i =0;i<length;i++){
list[i]=null;
}
}
public boolean add(Contact c){
boolean found = false;
int i = 0;
while(!found&&i<20){
if (list[i]==null){
list[i]=c;
found=true;
ptr=i;
}
i++;
}
return found;
}
public Contact find(String name){
boolean found=false;
int i =0;
while(i<contactLength&&!found){
ptr++;
if(ptr==contactLength){
ptr=0;
}
if(list[ptr]!=null){
if (list[ptr].getName().contains(name)){
found=true;
return list[ptr];
}
}
i++;
}
return null;
}
public Contact remove(){
Contact current= list[ptr];
list[ptr]=null;
return current;
}
public void displayContacts(){
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
System.out.println(list[i].toString());
}
else {
System.out.println("Empty:");//"Name:\nAddress:\nPhone\nComments:"
}
}
}
public boolean write (String fileName){
PrintWriter p = null;
try {
p = new PrintWriter(new File(fileName));
} catch (Exception e) {
return false;
}
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
p.println(list[i].toString());
}}
p.close();
return true;
}
public class Contact {
private String name;
private long phone;
private String address;
private String comments;
public void setName( String name){
this.name =name;
}
public String getName(){
return name;
}
public void setPhone(long phone){
this.phone=phone;
}
public long getPhone(){
return phone;
}
public void setAddress(String address){
this.address= address;
}
public String getAddress(){
return address;
}
public void setComments( String comments){
this.comments= comments;
}
public String getComments(){
return comments;
}
public String toString(){
return ("Name:\t\t"+name+"\nAddress:\t"+address+"\nPhone Number:\t"+phone+"\nComments:\t"+comments +"\n");
}
public Contact(String name, long phone, String address, String comments){
this.name=name;
this.phone=phone;
this.address=address;
this.comments=comments;
}
public boolean equals(Contact other){
if (this.name!=other.name){
return false;
}
if (this.phone!=other.phone){
return false;
}
if (this.address!=other.address){
return false;
}
if (this.comments!=other.comments){
return false;
}
return true;
}
Here is what I have so far...
public boolean read(String fileName){
Scanner s = null;
try {
s = new Scanner(new File(fileName));
} catch (Exception e) { // returns false if fails to find fileName
return false;
}
for(int i=0; i)
}
And YES I must use array! No lists! And nothing fancy please, this is an intro class, I won't understand it. Just scanner.
I see the pros and cons in the comment section, what about putting an end to the debate, given how you write I'm guessing you will need something like:
public static void read(String fileName){
try(BufferedReader in = new BufferedReader(new FileReader(fileName))){
String line = null;
String[] contact = new String[4];
int contactCounter = 0;
int buffer = 0;
while ((line = in.readLine()) != null){
buffer = line.split("\t").length - 1;
contact[contactCounter] = line.split("\t")[buffer];
contactCounter++;
if (contactCounter == 3){
new Contact(contact[0], contact[1], contact[2], contact[3]);
contactCounter == 0;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
I strongly suggest you improve how you serialize your Contact because this format is a mess, especially having not clear boundaries, the best I could figure was counting 4 EOL to create a new Contact.
Maybe have a look at csv format: https://en.wikipedia.org/wiki/Comma-separated_values
I am trying to get my addStudent() method in the Roster class to work here.
It's supposed to add a given student to this roster. If the student is already on the roster, or the numStudents == stopPoint, it doesn't change the roster and returns false. If it is successful it returns true.
Roster Class:
public class Roster {
Student[] students;
int numStudents;
int stopPoint;
Course course;
//constructor for this class initialize this roster to empty
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
}
//returns a string that represents the object for printing
public String toString()
{
String res = "";
for(int j = 0; j < numStudents; j++)
{
res = res + "\n" + students[j].toString();
}
return course + " " + numStudents + "/" + stopPoint+res;
}
//returns true if and only if the number of students in it is at stopPoint
public boolean isFull(int numStudents, int stopPoint)
{
if (numStudents == stopPoint)
{
return true;
}
else
return false;
}
/*add given student to this roster if student already on roster
or numStudents already == stopPoint, will not change roster and return
false but return true if successful, else false
*/
public boolean addStudent(Student student)
{
if(this.numStudents < this.stopPoint)
{
this.students[numStudents] = student; // here is where I get the error
this.numStudents++;
return true;
}
else
return false;
}
}
Testing Class:
public class TestRoster
{
public static void main(String[] args)
{
Student s1 = new Student("John","Doe");
Course c1 = new Course(198, 111);
Roster r1 = new Roster(4, c1);
System.out.println(r1);
testAdd(r1, s1);
}
private static void testAdd(Roster r, Student s)
{
System.out.println(s.familyName+" "+r.addStudent(s));
System.out.println(r);
}
}
Student Class:
public class Student
{
String personalName;
String familyName;
public Student(String pName, String fName)
{
personalName = pName;
familyName = fName;
}
public String toString( )
{
return "Student: " + familyName + ", "+ personalName;
}
}
Lastly, the Course Class:
public class Course
{
int deptNum;
int courseNum;
public Course(int deptNum, int courseNum)
{
this.deptNum = deptNum;
this.courseNum = courseNum;
}
public String toString( )
{
return deptNum + ":" + courseNum;
}
}
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at assign4.Roster.addStudent(Roster.java:56)
at assign4.TestRoster.testAdd(TestRoster.java:17)
at assign4.TestRoster.main(TestRoster.java:13)
Java Result: 1`
The other answers suggest using an arbitrary number for the array instansiation, this is not a good idea as you never know if it will be enough.
Your Roster class knows how many students there should be (via the constructor), you should initialize the Student array with stopPoint:
Student[] students;
int numStudents;
int stopPoint;
Course course;
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
this.students = new Student[this.stopPoint]
}
Since you can't touch your class variables, you can and should initialize the array within the constructor.
I'm trying to sort an array of records. But I get "not a Record" error. The method getCt() is in a different class, the program compiles and the array is of the record type. I really don't know what is wrong with this code.
HashTable:
public class HashTable {
private Record [] array;
private int size;
private int indexSize=0;
private boolean updated,found;
public HashTable(int m){
array= new Record[m];
size=0;
}
public void getCt() {
Arrays.sort(array);
// return array[0];
}
Record class:
import java.lang.Comparable;
import java.util.*;
public class Record implements Comparable {
private Integer count;
private DNSkey key;
public Record(DNSkey key) {
this.key = key;
count = 1;
}
public void update() {
count++;
}
public DNSkey getKey() {
return key;
}
public Integer getCount() {
return count;
}
public int compareTo(Object obj) {
if (!(obj instanceof Record)) {
throw new ClassCastException("Not a Record");
}
Record check = (Record) obj;
return getCount().compareTo(check.getCount());
}
public String toString() {
return getKey() + " " + getCount();
}
}
one easy way is to use generics :
public class Record implements Comparable<Record> {
...
public int compareTo(Record check){
return getCount().compareTo(check.getCount());
}
My guess would be null items in the array. "null instanceof Class" will return false.
This will throw the Exception:
Record[] array = new Record[] { new Record(...), null };
Arrays.sort(array);
Use generics! And an #Override annotation.