Null pointer exception in Java [duplicate] - java

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..

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 .

Java: Arraylist out of bounds when processing file [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act()
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage()
{
return mortgage;
}
public void setMortgage(String mortgage)
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH

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

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

Finding and removing an object from arraylist while not knowing the object's variables

I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar

Getting NullPointerException errors when trying to use multiple classes for the first time

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.

Categories