Java Array returning a NullPointerException [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'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];

Related

Getting NullPointerException on calling getter method [duplicate]

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.

How do you use methods from sub classes in the main class in Java?

I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.

Java cannot find symbol error - a method from another class

I'm trying to access the method changeAll from class MarkMaker the following way:
import java.util.Scanner;
class Question10e
{
public static void main(String[] args)
{
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Enter mark 1: ");
int newm1=input.nextInt();
System.out.print("Enter mark 2: ");
int newm2=input.nextInt();
System.out.print("Enter mark 3: ");
int newm3=input.nextInt();
String linem=input.nextLine();
System.out.print("Enter a master password: ");
String masterpass = input.next();
linem=input.nextLine();
MarkMaker mm = new MarkMaker(masterpass);
Mark masterMark1 = mm.makeMark(newm1);
Mark masterMark2 = mm.makeMark(newm2);
Mark masterMark3 = mm.makeMark(newm3);
try{
System.out.println("The new mark 1 is "+masterMark1.provisional(masterpass));
System.out.println("The new mark 2 is "+masterMark2.provisional(masterpass));
System.out.println("The new mark 3 is "+masterMark3.provisional(masterpass));
System.out.println("The new master password is is "+masterMark1.returnPass());
int avg = mm.average();
System.out.println("The average is "+avg);
changeAll(5.5, 3);
}
catch(IncorrectPasswordException e){}
}
}
This is the MarkMaker class:
import java.util.*;
class MarkMaker{
private String masterPass = "";
private ArrayList<Mark> masterArr = new ArrayList<Mark>();
public MarkMaker(String masterPass)
{
this.masterPass = masterPass;
}
public Mark makeMark(int m)
{
Mark newMarkObj = new Mark(m,masterPass);
masterArr.add(newMarkObj);
return newMarkObj;
}
public ArrayList<Mark> returnMasterArr()
{
return masterArr;
}
public int average() throws IncorrectPasswordException
{
int n = 0;
for(int i=0; i<masterArr.size(); i++)
{
n = n + masterArr.get(i).provisional(masterPass);
}
int avg = n/masterArr.size();
return avg;
}
public void changeAll(double d, int x) throws IncorrectPasswordException
{
for(int i=0; i<masterArr.size(); i++)
{
double currentMark = masterArr.get(i).provisional(masterPass);
System.out.println("Current mark is: "+currentMark);
currentMark = currentMark*d;
System.out.println("Current mark is: "+currentMark);
currentMark = Math.ceil(currentMark);
System.out.println("Current mark is: "+currentMark);
}
} }
And this is the Mark class:
class Mark
{
private int value;
private String password;
boolean released;
public Mark(int value, String password)
{
this.value = value;
this.password = password;
released = false;
}
public void release(String p) throws IncorrectPasswordException
{
if(p.equals(password))
{
if(released==false)
released = true;
}
else throw new IncorrectPasswordException(p);
}
public int value() throws UnReleasedException
{
if(released==true)
return value;
else
throw new UnReleasedException();
}
public int provisional(String p) throws IncorrectPasswordException
{
if(p.equals(password))
return value;
else
throw new IncorrectPasswordException(p);
}
public void change(String p, int arg) throws IncorrectPasswordException
{
if(p.equals(password))
value = arg;
else
throw new IncorrectPasswordException(p);
}
public String returnPass()
{
return password;
}
public boolean isReleased()
{
return released;
}
public boolean equals(Mark m2) throws UnReleasedException
{
if(this.isReleased() && m2.isReleased())
{ //it throws an error, that's why i'm using the Unreleased Exception
if(this.value()==m2.value())
return true;
}
throw new UnReleasedException();
} }
The problem is that I always get a "cannot find symbol error - method changeAll(double, int), location class Question10e"
Question10e doesn't have this method. Perhaps you intended to call this on an instance of a class which does like.
mm.changeAll(5.5, 3);
changeAll is a method which belongs to the MarkMaker class rather than the current Question10e class where you are attempting to call the method:
mm.changeAll(5.5, 3);
You need to call changeAll() through a MarkMarker object. It doesn't exist in your Question10e class. So, you could do this by:
mm.changeAll(5.5, 3)
Just because changeAll() is public doesn't mean that you can call it from anywhere. It simply means that a MarkMarker object can call it from anywhere.
You need
mm.changeAll(5.5, 3);

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

Problem in arranging contents of Class in JAVA

I have some classes and I'm trying to fill the objects of this class. Here is what i've tried. (Question is at the below)
public class Team
{
private String clubName;
private String preName;
private ArrayList<String> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<String>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<String> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<String> branches) { this.branches = branches; }
}
public class Branch
{
private ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() { return players; }
public void setPlayers(ArrayList<Player> players) { this.players = players; }
}
//TEST CLASS
public class test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String a,b,c;
String q = "q";
int brCount = 0, tCount = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Team[] teams = new Team[30];
Branch[] myBranch = new Branch[30];
for(int z = 0 ; z <30 ;z++)
{
teams[z] = new Team();
myBranch[z] = new Branch();
}
ArrayList<String> tmp = new ArrayList<String>();
int k = 0;
int secim = Integer.parseInt(input.readLine());
while(secim != 0)
{
if(k!=0)
secim = Integer.parseInt(input.readLine());
k++;
switch(secim)
{
case 1 :
brCount = 0;
a = input.readLine();
teams[tCount].setClubName(a);
b= input.readLine();
teams[tCount].setPreName(b);
c = input.readLine();
while(c.equals(q) == false)
{
if(brCount != 0)
{c = input.readLine();}
if(c.equals(q)== false){
myBranch[brCount].brName = c;
tmp.add(myBranch[brCount].brName);
brCount++;
}
System.out.println(brCount);
}
teams[tCount].setBranches(tmp);
for(int i=0;i<=tCount;i++ ){
System.out.print("a :" + teams[i].getClubName()+ " " + teams[i].getPreName()+ " ");
System.out.println(teams[i].getBranches());}
tCount++;
break;
case 2:
String src = input.readLine();//LATERRRRRRRr
}
}
}
}
The problem is one of my class elements. I have an arraylist as an element of a class.
When i enter:
AAA as preName
BBB as clubName
c
d
e as Branches
Then as a second element
www as preName
GGG as clubName
a
b as branches
The result is coming like:
AAA BBB c,d,e,a,b
GGG www c,d,e,a,b
Which means ArrayList part of the class is putting it on and on. I tried to use clear() method but caused problems. Any ideas.
The problem is that the two Team objects are sharing the same reference to a single ArrayList<String>. There are many ways to solve this, but one way is to let Team manage its own List<Branch>, and it should only expose an add(Branch) instead of setBranches(List<Branch>). This would hide most information from the client, exposing only the most essential functionalities, which is a good thing.
Note also that I use the interface List<Branch> instead of ArrayList<Branch> (or ArrayList<String>). This is in accordance with Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces.
I also recommend using java.util.Scanner for the I/O. Look at the API for examples, and there are many questions on stackoverflow about it as well. It'd make the code much simpler.
You need to copy lists in setters, otherwise you are using the same list (tmp) everywhere, so no wonder it has the same contents:
public void setBranches(List<String> branches) {
this.branches = new ArrayList<String>(branches);
}
public void setPlayers(List<Player> players) {
this.players = new ArrayList<Player>(players);
}
Theoretically, you also need to copy or wrap it in getters, but that's another story.

Categories

Resources