Getting NullPointerException on calling getter method [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am having three classes StudentMain, StudentService, Student. Student class contains getters and setters method and from StudentMain I'm passing Student object to StudentService. Below is the code:
code for StudentMain:
public class StudentMain {
static Student data [] = new Student[4];
static { for (int i = 0; i < data.length; i++)
data [i] =new Student();
data [0] = new Student ("Sekar", new int [] {35, 35, 35});
data [1] = new Student(null,new int[]{11,22,33});
data [2] = null;
data [3] = new Student ("Manoj", null);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentService studentService = new StudentService ();
System.out.println ("Number of Objects with Marks array as null =" + studentService.findNumberOfNullMarks (data));
System.out.println ("Number of Objects with Name as null="+ studentService.findNumberOfNullNames(data));
System.out.println ("Number of Objects that are entirely null="+ studentService.findNumberOfNullObjects(data));
}
}
code for Student:
public class Student {
private String name;
private int marks[];
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setMarks(int [] marks) {
this.marks=marks;
}
public int[] getMarks() {
return marks;
}
public Student() {
}
public Student(String name,int[] marks) {
setName(name);
setMarks(marks);
}
}
code for StudentService:
public class StudentService{
Student[] data;
public int findNumberOfNullMarks(Student data[]) {
this.data=data;
int count=0;
int i=0;
while(i!=data.length) {
if(data[i].getMarks()==null)
count++;
i++;
}
return count;
}
public int findNumberOfNullNames(Student data[]) {
int count=0;
int i=0;
while(i!=data.length) {
if(data[i].getName()==null)
count++;
i++;
}
return count;
}
public int findNumberOfNullObjects(Student data[]) {
int count=0;
int i=0;
while(i!=data.length) {
if(data[i]==null)
count++;
i++;
}
return count;
}
}
I am getting exception at if(data[i].getMarks()==null) and if(data[i].getMarks()=null) in StudentService class.

data [0] = new Student ("Sekar", new int [] {35, 35, 35});
data [1] = new Student(null,new int[]{11,22,33});
data [2] = null;
data [3] = new Student ("Manoj", null);
for i = 0, data[0] having object and having array marks in object so you will not get java.lang.NullPointerException
for i = 1, data[1] having object and having array marks in object so you will not get java.lang.NullPointerException
for i = 2, data[2] having null so you will get java.lang.NullPointerException
for i = 3, data[3] having having object but array marks is null so you will get java.lang.NullPointerException
So you need to make sure you should have object and array.

Related

Print an array in tester class

I am trying to return the array of students in a tester class for the Course class but I keep getting a .class expected error. I've tried to do
students[].TestCourse but that doesn't work either.
public class Course {
private String courseName;
private String[] students = new String[4];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
if (numberOfStudents == students.length) {
String [] copy = new String [students.length*2];
System.arraycopy(students,0,copy,0,students.length);
students = copy;
}
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public void dropStudent(String student) {
for (int i=0;i<students.length;i++) {
if (students[i]==student) {
students[i] = null;
}
for (i=i;i<students.length-1;i++) {
students[i] = students[i+1];
}
}
}
}
public class TestCourse {
public static void main() {
Course compScience = new Course("Computer Science");
compScience.addStudent("Jack");
compScience.addStudent("Dean");
compScience.addStudent("Leon");
compScience.dropStudent("Dean");
System.out.println("The students currently in this course are "+ students[]);
}
}
Change the line in your main method to:
System.out.println("The students currently in this course are "+ Arrays.toString(compScience.getStudents()));
and it should fire up!
All you've done is try to call the field of a class directly when you need to access it via the reference you created Course compScience = new Course("Computer Science"); ... then call it's method getStudents() as follows compScience.getStudents(). To get the contents of the array you then need to wrap this method call in Arrays.toString() as above.

Java Array returning a NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm tring to print all the elements in the Car array. But the console shows it has null pointer problem.
Assume I have a class named Car, and there is nothing wrong in Car class. CarLeadership class manipulates group of Car objects. I put them in an array called carArr(one attribute in CarLeadership class).
public class CarLeadership {
private Car[] carArr;
private int position; //point to the current element of carDatabase
//pass length of array
public CarLeadership(int maxCar) {
Car[] carArr = new Car[maxCar];
position=0;
}
//parameterized constructor
public CarLeadership(Car[] carDatabase,int position) {
carArr = carDatabase;
this.position = position;
}
//copy constructor
public CarLeadership(CarLeadership c) {
this.carArr = c.getCarArr();
this.position = c.position;
}
public void setCarArr(Car[] carArr) {
this.carArr = carArr;
}
public void setCarArrElements(int index,Car carObj) {
if(index >= carArr.length) {
System.out.println("Index out of bounds");
System.exit(0);
}
carArr[index] = carObj;
}
public Car[] getCarArr() {
//deep copy
Car[] anotherCarArr = new Car[this.carArr.length];
for(int i=0; i<anotherCarArr.length;i++)
anotherCarArr[i] = this.carArr[i];
return anotherCarArr;
}
public void setPosition(int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public String toString() { //instance has carArr
String s="";
for(int i=0;i<carArr.length;i++)
if(carArr[i]!= null)
s += ("Car: # "+ i + "\nMake: " +this.carArr[i].getMake()
+"\nModel: "+this.carArr[i].getModel()
+"\nYear: "+this.carArr[i].getYear()
+"\nPrice: "+this.carArr[i].getPrice()+"\n");
return s;
}
}
//driver class
public class CarLeadershipDriver {
public static void main(String[] args) {
// TODO Auto-generated method stub
CarLeadership cc = new CarLeadership(5);
cc.setCarArrElements(0,new Car("aa","cc",2018,242));
cc.setCarArrElements(1,new Car("aa","aa",2018,242));
cc.setCarArrElements(2,new Car("aa","cc",2018,242));
System.out.println(cc);
}
}
The error message:
Exception in thread "main" java.lang.NullPointerException
at CarLeadership.setCarArrElements(CarLeadership.java:31)
at CarLeadershipDriver.main(CarLeadershipDriver.java:7)
Change your constructor
public CarLeadership(int maxCar) {
Car[] carArr = new Car[maxCar];
position = 0;
}
to
public CarLeadership(int maxCar) {
carArr = new Car[maxCar];
position = 0;
}
that's all.
Now your program run with output:
Car: # 0
Make: aa
Model: cc
Year: 2018
Price: 242
Car: # 1
Make: aa
Model: aa
Year: 2018
Price: 242
Car: # 2
Make: aa
Model: cc
Year: 2018
Price: 242
The issue is that you are initializing a local copy of carArr in your constructor.
Replace
//pass length of array
public CarLeadership(int maxCar) {
Car[] carArr = new Car[maxCar];
position=0;
}
with
//pass length of array
public CarLeadership(int maxCar) {
carArr = new Car[maxCar];
position=0;
}
or if you want to be more explicit
//pass length of array
public CarLeadership(int maxCar) {
this.carArr = new Car[maxCar];
position=0;
}
You created new array in your constructor, while you should assign the declared size to the existing array.
this.carArr = new Car[maxCar];

How to return an array in .toString method

How can I return an array in this .toString method of my Shelf class?
public class Book
{
int wys, szer;
String imie, tytul;
public Book(int wys, int szer, String imie, String tytul)
{
this.wys = wys;
this.szer = szer;
this.imie = imie;
this.tytul = tytul;
}
#Override
public String toString()
{
return imie;
}
}
public class Shelf
{
int wys;
private Book book[] = new Book[20];
public Shelf(Book[] ks, int j)
{
for (int i = 0; i < ks.length - 1; i++)
{
this.book[i] = ks[i];
}
}
#Override
public String toString()
{
for (int i=0;i<book.length;i++)
{
return book[i].toString();
}
}
}
Main class
public class Test
{
public static void main(String[] args)
{
Book ks[]={
new Book (13,2, "Rhonda Byrne", "Sekret"),
new Book(12, 1, "Graham Greene", "Monsignore Kichote"),
new Book(19, 3, "Hugo Steinhaus", "Slownik racjonalny"),
new Book(10, 4, "RE.M. Remarque", "Trzej towarzysze"),
new Book(13, 3, "A.A. Milne", "Kubus Puchatek"),
new Book(11, 4, "Paulo Coelho", "El Aquimista"),
new Book(13, 5, "Mitch Albom", "Tuesday with Morrie"),
new Book(11, 2, "John Fowles", "Mag"),
};
Shelf s = new Shelf(ks, 15);
System.out.println(s);
}
}
It is doesn't want to compile if the return statement is in the loop.
It will compile if I return in that way:
return book[0].toString+book[1].toString... etc....
But how to do it automatically?
--->I Updated all of the code of a class.
The Arrays utility class has a method to create a string from an array.
return Arrays.toString(book);
public String toString()
So you must return a String.
I suggest using A StringBuilder and Appending to it in your loop.
public String toString()
{
StringBuilder sb =new StringBuilder();
for (int i=0;i<book.length;i++)
{
sb.append(book[i].toString());
}
return sb.toString();
}
You are getting A NullPointerException Because of the way you initialize your Array
private Book book[] = new Book[20];
Change That to something like this:
private Book book[] ;
public Shelf(Book[] ks, int j)
{
book=new Book[ks.length];
for (int i = 0; i < ks.length ; i++)
{
this.book[i] = ks[i];
}
}
Maybe calling the method in a loop?
Then you need a parameter and you can use the method on every element of the array.
for (int i=0; i<book.length; i++) {
toString(int i);
}
And the method:
public String toString(int i) {
return book[i].toString();
}
Not nice, but maybe it helps.
This day and age, I would suggest something along these lines:
#Override
public String toString() {
return Arrays.stream(book).map(Book::toString)
.collect(Collectors.joining(", "));
}

"Cannot find symbol" error when using methods and arrays in Java [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 7 years ago.
I have a class called Student with data members:
private String name;
private long idNumber;
With correct getter and setter methods.
I need to create a tester class called StudentTest which includes the following methods:
public static Student[] createArray()
public static void populateArray(Student[] array)
public static void displayArray(Student[] array)
I am getting a "cannot find symbol" error when I try to compile my tester class.
Here is my tester class:
// Scanner class from the Java API
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) {
// Call methods
Student[] studentList = createArray();
populateArray(studentList);
displayArray(studentList);
} // end main
// Create Array Method
public static Student[] createArray() {
// Declaration & Creation of Scanner object
Scanner input = new Scanner(System.in);
// Create Array
System.out.println("Enter size of array: ");
int i = input.nextInt();
Student[] studentList = new Student[i];
return studentList;
}
// Populate Array Method
public static void populateArray(Student[] array) {
for(int i = 1; i < studentList.length; i++) {
studentList[i] = new Student();
Scanner userInput = new Scanner(System.in);
// Get Input for Name
System.out.println("Enter Student Name: ");
studentList[i].setName = userInput.nextLine();
// Get Input for Id Number
System.out.println("Enter Student ID Number: ");
studentList[i].setIdNumber = userInput.nextInt();
}
}
// Display Array Method
public static void displayArray(Student[] array) {
System.out.println("Array Contents");
for(int j = 0; j < studentList.length; j++) {
System.out.println(studentList[j].getName() + " " + studentList[j].getIdNumber());
}
}
} // end class
Please can anyone help me out, I am quite new to java.
My Student class
public class Student {
// Data Members
private String name;
private int idNumber;
// Constructor
public Student() {
name = "Unassigned";
idNumber = 0;
}
// Getters
public String getName(){
return name;
}
public int getIdNumber(){
return idNumber;
}
// Setters
public void setName(String name){
this.name = name;
}
public void setIdNumber(int idNumber){
this.idNumber = idNumber;
}
} // end class
The symbol that can't be found is to do with the array itself studentList
populateArray (and displayArray) are trying to use studentList, but you named it array in the arguments. Rename it, like
public static void populateArray(Student[] studentList) { // <-- not array.
public static void displayArray(Student[] studentList) { // <-- and here.
or use array instead of studentList in your methods.

Exception in thread "main" java.lang.NullPointerException on Java Array

I'm getting this error from my code:
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:20)
Could anyone identify the error, I think it has something to do with initializing my array?
MainClass.java
public class MainClass {
public static void main(String[] args) {
//dummy vars to simulate user input
double price = 2.75;
//declare an array of wincalcs
WinCalc[] staging1;
staging1 = new WinCalc[100];
for (int x=0; x<staging1.length; x++ ) {
staging1[x].price = price;
staging1[x].quantity = x+1;
staging1[x].calcTotal();
}
}
}
WinCalc.java
public class WinCalc {
public double price;
public double quantity;
public double total;
public WinCalc () {
price= 0;
quantity = 0;
total = 0;
}
public void calcTotal() {
this.total = price * quantity;
}
}
You forgot to create the objects
for (int x=0; x<staging1.length; x++ ) {
staging1[x] = new WinCalc();
// ...
}
When you allocate your array, it is initially populated with null entries. In order for it to contain actual objects, you must manually populate will newly allocated objects:
WinCalc[] staging1;
staging1 = new WinCalc[100];
for(int n = 0; n < 100; n ++)
{
stanging1[n] = new WinClac();
}
This is because all objects in java are references which by default point to nowhere.
Update your code with this:
public class MainClass {
public static void main(String[] args) {
//dummy vars to simulate user input
double price = 2.75;
//declare an array of wincalcs
WinCalc[] staging1;
staging1 = new WinCalc[100];
for (int x=0; x<staging1.length; x++ ) {
staging1[x] = new WinCalc();
staging1[x].price = price;
staging1[x].quantity = x+1;
staging1[x].calcTotal();
}
}
Cases that we get NullPointerException are accessing/modifying the field of null object or accessing/modifying the slot of null as if it were an array or taking the length of null as if it were an array.
//Let us have a Person class
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String toString(){
return "[Name->"+ getName() +" ,Age->"+getAge()+"]";
}
}
//The main class simulate collection of persons using array
import java.util.Arrays;
public class ListOfPersonIn {
public static void arrayManipulation()
{
Person[] persons=new Person[3]; // Array of Person to conatain 3 persons
Person titi=new Person("Titi", 35);
Person beti=new Person("Beti", 10);
Person nati=new Person("nati", 18);
// Display list of persons
for(Person person:persons){
System.out.println(person.toString());
}
//Double array size, copy the old value to the new array and add new persons
Person[]newPersons=copyArraySize(persons);
System.out.println("Loop through a new Array ");
for(Person person: newPersons){
System.out.println(person.toString());
}
}
// Private method to resize array, copy the old array to the new array and add new list of persons
private static Person [] copyArraySize(Person [] persons)
{
Person[]newPersons=Arrays.copyOf(persons, persons.length*2);
// newPersons[persons.length]=new Person("meti", 50); in this case we get NullPointerException because the new array has length 6 but only 4 data is populated the reaming 2 indices are not populated i.e newArray[4] and newArray[5] are null value so it raised NullPointerException. Not to get NullPointerException just populate all array indices with data
for(int i=persons.length;i< newPersons.length;i++){
newPersons[i]=new Person("meti", 50);//duplicate data, array can’t maintain uniqueness like set
}
return newPersons;
}
public static void main(String[] args) {
arrayManipulation();
}
}

Categories

Resources