NullPointerException in group class. can't find an array object [duplicate] - java

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

Related

Array of class objects are null even after initializing them with new keyword [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
Closed 9 months ago.
I have two classes named RRT and MyClass. RRT class has some data members and for each of them it has respective getter and setter method. From the main method of MyClass I am creating an array of RRT objects and trying to set values to data members using the object's setter method but receiving an error saying object is null.
RRT.java
public class RRT {
private int ticketNo;
private String raisedBy;
private String assignedTo;
private int priority;
private String project;
// getters
public int getPriority() {
return priority;
}
public int getTicketNo() {
return ticketNo;
}
public String getAssignedTo() {
return assignedTo;
}
public String getProject() {
return project;
}
public String getRaisedBy() {
return raisedBy;
}
// setters
public void setAssignedTo(String assignedTo) {
this.assignedTo = assignedTo;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setProject(String project) {
this.project = project;
}
public void setRaisedBy(String raisedBy) {
this.raisedBy = raisedBy;
}
public void setTicketNo(int ticketNo) {
this.ticketNo = ticketNo;
}
}
MyClass.java
class MyClass{
public static RRT getHighestPriorityTicket(RRT[] rrt, String value){
RRT highestPriority = null;
int high = Integer.MAX_VALUE;
for(RRT i : rrt){
if(i.getProject().compareToIgnoreCase(value)==0 && i.getPriority()<high){
high = i.getPriority();
highestPriority = i;
}
}
return highestPriority;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number = 4;
RRT[] ob = new RRT[number];
for (int i = 0; i <number ; i++) {
String ticketNumber = sc.next();
String raisedBy = sc.next();
String assignedTo = sc.next();
String priority = sc.next();
String project = sc.next();
ob[i].setAssignedTo(assignedTo);
ob[i].setPriority(Integer.parseInt(priority));
ob[i].setRaisedBy(raisedBy);
ob[i].setTicketNo(Integer.parseInt(ticketNumber));
ob[i].setProject(project);
}
String targetProject = sc.next();
RRT answer = getHighestPriorityTicket(ob,targetProject);
if(answer!=null){
System.out.println(answer.getTicketNo());
System.out.println(answer.getRaisedBy());
System.out.println(answer.getAssignedTo());
}
else {
System.out.println("No such Ticket");
}
}
}
Can anyone tell me what is wrong with the code .

Null pointer exception in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am really new to programming and I am trying to get a student inventory set up and validate the input by checking each field.
It contains attendance for 10 days and I need to validate each field that its either Yes/No. And I am assigning them to class fields using getter/setter methods. Since Attendance is series of 10 inputs, I am assigning them as a list and passing them as a parameter to the set method and assign them to Class array.
Though the list is not empty, assigning it to array is throwing 'Null pointer exception' and unable to figure out why.
import java.util.*;
public class Studentdetail {
String studentName;
String studentId;
String classCode;
String[] attendence;//={"no"," yes", "yes"," no", "yes"," yes", "yes", "yes"," no"," yes"};
String test1;
String test2;
String tutorial;
String exams;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getClassCode() {
return classCode;
}
public void setClassCode(String classCode) {
this.classCode = classCode;
}
public String[] getAttendence() {
return attendence;
}
private void setAttendence(List<String> studentList) {
int j=1;
for(String attList: studentList){
if(attList != null){
attendence[j]= attList;
}
j++;
}
}
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public String getTest2() {
return test2;
}
public void setTest2(String test2) {
this.test2 = test2;
}
public String getTutorial() {
return tutorial;
}
public void setTutorial(String tutorial) {
this.tutorial = tutorial;
}
public String getExams() {
return exams;
}
public void setExams(String exams) {
this.exams = exams;
}
public static void main(String[] args) {
String sampleInput = "S0032124, Tan ah cat, ICT310-FT02, no, yes, yes, no, yes, yes, yes, yes, no, yes, 43, 55, 12, 53";
ArrayList<String> studentList = new ArrayList<String>();
for (String s : sampleInput.split(",")) {
studentList.add(s);
}
Studentdetail newStudent = new Studentdetail();
newStudent.setStudentId(studentList.get(0));
newStudent.setStudentName(studentList.get(1));
newStudent.setClassCode(studentList.get(2));
newStudent.setAttendence(studentList.subList(3, 12));
newStudent.setTest1(studentList.get(13));
newStudent.setTest2(studentList.get(14));
newStudent.setTutorial(studentList.get(15));
newStudent.setExams(studentList.get(16));
boolean value;
value = classCodeValidator(newStudent.getClassCode());
value = stuAttValidator(newStudent.getAttendence());
if (value == true)
System.out.println("Class code verified "
+ newStudent.getClassCode());
else
System.out.println("Class code invalid "
+ newStudent.getClassCode().trim().substring(6,7));
}
public boolean stuIdValidator(String stuId) {
if (stuId.length() == 8) {
if (stuId.substring(0, 1) == "S")
return true;
}
return false;
}
public static boolean classCodeValidator(String classCode) {
// ICT303-FT07
if (classCode.trim().length() == 11)
if (classCode.trim().substring(6,7).equals("-"))
if (classCode.trim().substring(1,7).length() == 6)
if (classCode.trim().substring(7, 11).length() == 4)
return true;
return false;
}
public static boolean stuAttValidator (String[] stuAtten){
for(String attMarker: stuAtten){
if(attMarker.equalsIgnoreCase("YES") || attMarker.equalsIgnoreCase("NO"))
return true;
}
return false;
}
}
First you need to initialize your string array attendence.
string[] attendence;
private void setAttendence(List<String> studentList) {
int j=1;
for(String attList: studentList){
if(attList != null){
attendence[j]= attList; // getting null pointer exception
}
j++;
}
}
public static void main(String[] args) {
String sampleInput = "S0032124, Tan ah cat, ICT310-FT02, no, yes, yes, no, yes, yes, yes, yes, no, yes, 43, 55, 12, 53";
ArrayList<String> studentList = new ArrayList<String>();
for (String s : sampleInput.split(",")) {
studentList.add(s);
}
attendence = new string[36];
newStudent.setAttendence(studentList.subList(3, 12));
}
Otherwise you can not reach a value from attendence because it is just a pointer indicates null.
If you are familliar with lower level programming languages, arrays are pointers and they need to show beginning of allocated memory space. By saying new string[n] you allocate n*sizeof(string) bytes memory space. So if you say attendence[1] you will reach location of &attendence + sizeof(string).
By the way string is a char array so you actually get pointer of pointer. I mean sizeof(string) = 1 word..

Java: Trying to create a database that stores

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);

Print array variables, not variable pointer locations [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I am working on a project from a Java text book, and I have come across an issue. I am attempting to print the variables in an array, however it continually prints the variables location (#hex code) instead of the actual variable... I believe I am attempting to print the array correctly via using a 'for loop'. I have attached my code below...
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
}
//Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
}
Any and all guidance is appreciated. Thank You!
You need to override the toString method in your Person class.
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName) { ... }
public String getName() { ... }
public int compareTo(Person o) { ... }
#Override
public String toString() {
return "My name is " + name; // For the example, you could return any String you want
}
}
the toString method is generally used to provide a description of the object.

How to call a method in another class using the arraylist index in java?

Currently I have two classes. A Classroom class and a School class.
public void addTeacherToClassRoom(Classroom myClassRoom, String TeacherName)
I would like my method addTeacherToClassRoom to use the Classroom Arraylist index number to setTeacherName
e.g.
int 0 = maths
int 1 = science
I would like to setTeacherName "Daniel" in int 1 science.
many, thanks
public class Classroom
{
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName)
{
classRoomName = newClassRoomName;
}
public String returnClassRoomName()
{
return classRoomName;
}
public void setTeacherName(String newTeacherName)
{
teacherName = newTeacherName;
}
public String returnTeacherName()
{
return teacherName;
}
}
import java.util.ArrayList;
public class School
{
private ArrayList<Classroom> classrooms;
private String classRoomName;
private String teacherName;
public School()
{
classrooms = new ArrayList<Classroom>();
}
public void addClassRoom(Classroom newClassRoom, String theClassRoomName)
{
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
public void addTeacherToClassRoom(Classroom myClassRoom, String TeacherName)
{
myClassRoom.setTeacherName(TeacherName);
}
}
I think you're asking to do something like this:
public void addTeacherToClassRoom(int classroomId, String TeacherName)
{
if (classroomId < classrooms.size() ) {
classrooms.get(classroomId).setTeacherName(TeacherName);
}
}
This will access one of the Classroom objects in classrooms, and call the setTeacherName method on it.
I believe the method you are looking for is classRooms.indexOf(myClassRoom). This should return the index of the classroom you are looking for.
However, for this to work reliably you should override and implement the hashCode() and equals() method on the Classroom class.
public void addTeacherToClassRoom(Classroom myClassRoom, String teacherName){
int index = classrooms.indexOf(myClassRoom);
if(index == -1){
//The classroom isn't in the list yet.
myClassRoom.setTeacherName(teacherName);
classrooms.add(myClassRoom);
}else{
//Just update the teacher on the existing classroom.
classrooms.get(index).setTeacherName(teacherName);
}
}
public void addTeacherToClassRoom(Classroom myClassRoom, String TeacherName)
{
myClassRoom.setTeacherName(TeacherName);
classRooms.add(myClassRoom);
}
Is this enough?

Categories