how do if fix the NullPointerException on an arrylist? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
how do if fix the Exception in thread "main" java.lang.NullPointerException
at BankSystem.Branches.findCustomer(Branches.java:44)
I'm new to coding and java is my first language and I keep getting this error I don't know to fix it.
package BankSystem;
import java.util.ArrayList;
public class Branches {
private String name;
private ArrayList<Customers> newCustomer;
public Branches(){
}
public Branches(String name) {
this.name = name;
this.newCustomer = new ArrayList<>();
}
public ArrayList<Customers> getNewCustomer(){
return newCustomer;
}
public String getName() {
return name;
}
public boolean addCustomer(String name, double amount) {
if (findCustomer(name) == null) {
this.newCustomer.add(new Customers(name, amount));
return true;
}
return false;
}
public boolean addTranstraction(String name, Double amount) {
Customers existingCustomer = findCustomer(name);
if (existingCustomer != null) {
existingCustomer.addTransactions(amount);
return true;
}
return false;
}
private Customers findCustomer(String name) {
for(int i=0; i<this.newCustomer.size(); i++){
Customers checkedCustomer = this.newCustomer.get(i);
if(checkedCustomer.getName().equals(name)) {
return checkedCustomer;
}
}
return null;
}
}

I think that the default constructor for your class is being called, which doesn't initialize newCustomer. You would need to look at the code that initializes the Branch that is giving you the error. The NullPointerException just means that you are trying to use an object that has not been initialized.

The problem in your findCustomer might be that if the customer you are looking for in addTranstraction does not exist, which would cause it to return null, and trying to access a null variable is what causes your nullPointerException.

Related

java.lang.Object cannot be converted to the class i created [duplicate]

This question already has answers here:
What are Generics in Java? [closed]
(3 answers)
Closed 3 years ago.
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code
public class Test1
{
public static void main(String args[])
{
Thing whipersnaper = new Thing(30, "whipersnaper");
List storage = new List();
storage.insert(whipersnaper);
Thing x = storage.getItem(0);
x.doubleWeight();
System.out.println(x.getWeight());
}
}
here is the "Thing" class
public class Thing
{
private int weight;
private String name;
public Thing(int weight,String name){
this.weight = weight;
this.name = name;
}
public void doubleWeight(){
this.weight *= 2;
}
public int getWeight(){
return this.weight;
}
}
finally here is the List class
public class List
{
private Object[] itemList;
private int size;
public List()
{
this.itemList = new Object[10];
this.size = 0;
}
public void insert(Object item){
itemList[size] = item;
size++;
}
public Object getItem(int index){
return itemList[index];
}
}
i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.
Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);
Thing x = (Thing) storage.getItem(0);

My getName() function is coded right but throws an NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
So I was trying to code a viewer class and then create a list which is based on these viewers as another Class called ViewerList.
Usually everything should work but somehow it doesn't let me use the methods "toLine()" and "getName()". If anyone here could help me it would be awesome.
As in title the only error-report i get is NullPointerException.
This is the Viewer class:
public class Viewer {
private int points = 0;
private String name;
public Viewer(String name, int points) {
this.points = points;
this.name = name;
}
public int getPoints() {
return points;
}
public String toLine() {
String line = getName() + " " + getPoints();
return line;
}
public void addPoint(int amount){
points += amount;
}
public String getName(){
return name;
}
This is the ViewerList class:
public class ViewerList {
private Viewer[] array;
private int nextFreeSlot = 0;
private int count = 0;
public ViewerList(int capacity){
array = new Viewer[capacity];
}
public void add(Viewer o){
if (nextFreeSlot == array.length) {
throw new IllegalStateException("Liste ist voll!");
}
array[nextFreeSlot] = o;
count++;
nextFreeSlot++;
}
public Viewer[] getArray(){
return array;
}
public Viewer get(int index) {
return array[index];
}
public int getCapacity() {
return array.length;
}
public int getElementCount() {
return count;
}
public void addPoints () {
if(array.length > 0){
for(Viewer v : array){
v.addPoint(1);
}
}
}
public int getPointsOf(String viewerName) {
int points = 0;
String vName = "";
for(Viewer v : array){
vName = v.getName(); // The v.getName() method is an error here
if(viewerName.equals(vName)) {
points = v.getPoints();
}
}
return points;
}
public boolean contains(String name) {
boolean contains = false;
for(Viewer v : array){
if(name.equals(v.getName())){ // also here i get the NullPointerException
contains = true;
break;
}
}
return contains;
}
}
Also if you need the stack trace then here it is:
java.lang.NullPointerException
at bot.PointList.getPointsOf(PointList.java:50)
Null pointer exception occurs when you do not initialize the declared variable. My guess in your case is the string name. Debug your code by adding a print statement in your getName() method.

java.lang.nullpointer error in linkedlist in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to make a student registration interface with several classes, provided in the requirement. In doing so, the linkedlist in my CourseFactory class is showing a null pointer.
public class Course {
private String id;
private String title;
private int credit;
private int tuitionPerCredit;
public void setId(String id){
this.id=id;
}
public String getId(){
return this.id;
}
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return this.title;
}
public void setCredit(int credit){
this.credit=credit;
}
public int getCredit(){
return this.credit;
}
public void setTuitionPerCredit(int tuitionPerCredit){
this.tuitionPerCredit=tuitionPerCredit;
}
public int getTuitionPerCredit(){
return tuitionPerCredit;
}
public int getSubTotal(){
return this.credit*this.tuitionPerCredit;
}
}
And CourseFactory class
import java.util.LinkedList;
import static android.R.attr.id;
public class CourseFactory {
LinkedList<Course> cList;
public void CourseFactory(){
Course course = new Course();
course.setId("CSE327");
course.setTitle("SOFT ENG");
course.setCredit(3);
course.setTuitionPerCredit(1500);
cList.add(course);
Course course1 = new Course();
course1.setId("CSE115");
course1.setTitle("INTRO C");
course1.setCredit(3);
course1.setTuitionPerCredit(1500);
cList.add(course1);
Course course2 = new Course();
course2.setId("CSE215");
course2.setTitle("INTRO JAVA");
course2.setCredit(3);
course2.setTuitionPerCredit(1500);
cList.add(course2);
Course course3 = new Course();
course3.setId("CSE225");
course3.setTitle("DATA STRUCT");
course3.setCredit(3);
course3.setTuitionPerCredit(1500);
cList.add(course3);
Course course4 = new Course();
course4.setId("CSE373");
course4.setTitle("ALGOR.");
course4.setCredit(3);
course4.setTuitionPerCredit(1500);
cList.add(course4);
}
public Course getCourse(String id){
int temp = 0;
for(int i=0;i<cList.size();i++) {
if (cList.get(i).getId().equals(id)) {
temp=i;
break;
}
}
return cList.get(temp);
}
}
The error is on the line "if (cList.get(i).getId().equals(id))
You have to initialize LinkedList. Or else it will get null-pointer exception.
LinkedList<Course> cList=new LinkedList<Course>();
You need to initialize cList before use
LinkedList<Course> cList=new LinkedList<Course>();
or better, initialize into CourseFactory's constructor
public void CourseFactory(){
cList=new LinkedList<Course>();
Course course = new Course();
...
...
}
diamond operator is supported in -source 7 or higher
LinkedList<Course> cList=new LinkedList<>();

Blue J - identifier expected message? [duplicate]

This question already has answers here:
Java Reserve Keywords
(4 answers)
Closed 7 years ago.
i'm writing the following code and i'm getting the error 'identifier expected' on the line
private String class;
public class Records
{
private String name;
private String class;
private int cabinNumber;
public Records(String n, String c, int cn)
{
name = n;
class = c;
cabinNumber = cn;
}
public void setClass (String c){
class = c;
}
public void set cabinNumber (int cn){
cabinNumber = cn;
}
public String name(){
return name;
}
public String class(){
return class;
}
public int cabinNumber(){
return cabinNumber;
}
}
can someone please explain why this is happening and what I can do to fix it?
thank you!
class is a java keyword, you cannot have a variable with this name.

java.lang.NullPointerException error how to fix? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
having problem with null pointer exception and i read few article bout that error and still coundnt figure out what the problem.
The error happen at CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);
topIndex=0 by the way.
Can anyone highlight the problem im having?
here my class
public class Schedulingtest {
public static void main (String[] args) throws IOException
{
Scanner fileScan;
fileScan=new Scanner(new File("data.txt"));
Schedule compatibility = new Schedule();
while(fileScan.hasNext())
{String url=fileScan.nextLine();
compatibility.addActivity(url);
}
}
public class Schedule{
import java.util.Scanner;
import java.util.Arrays;
public class Schedule {
Activity[] CompatibleActivity;
int totalTime=0,topIndex=0;
Scanner urlScan;
public Schedule(){
Activity[] CompatibleActivity=new Activity[30];
}
public int getTotalTime()
{return totalTime;
}
public void addActivity(String entry){
urlScan=new Scanner(entry);
urlScan.useDelimiter(" ");
String c=null;
int aNum = 0,bNum=0;
while(urlScan.hasNext())
{String a=urlScan.next();
String b=urlScan.next();
c=urlScan.next();
aNum=Integer.parseInt(a);
bNum=Integer.parseInt(b);
}
CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);
topIndex++;
System.out.println("Activity added: start "+aNum+ " stop "+bNum+" "+c );
}
}
Activity Class
public class Activity {
private int start,stop,duration;
private String name;
public Activity(int Start,int Stop,String Name)
{
start=Start;
stop=Stop;
name=Name;
duration=Stop-Start;
}
public String getName()
{return name;
}
public int getStart()
{return start;
}
public int getStop()
{return stop;
}
public int getDuration()
{return duration;
}
public boolean compatible(int Start1,int Stop1,int toMatchsideStart,int toMatchsideStop)
{
int Start=Start1;
int Stop=Stop1;
int toMatchStart=toMatchsideStart;
int toMatchStop=toMatchsideStop;
if(toMatchStop<=Start)
{return true;
}
if(toMatchsideStart>=Stop)
{return true;
}
else
{return false;}
}
public String toString()
{return( name+"<"+start+","+stop+">"); }
}
Most likely you have CompatibleActivity declared in your class as
private Activity[] CompatibleActivity;
which declares a reference and initializes it to null by default. You need to assign it a real array with enough elements (e.g. in your constructor):
CompatibleActivity = new Activity[myBigNumber];
If the NullPointerException is definitely on that line, then it can only be caused by CompatibleActivity being null. You will need to find in your code where that Array Object is declared and make sure that it is also instantiated, e.g.
Activity[] CompatibleActivity = new Activity[size];
Check if you've initialized the array before you access one of its cells. You need an expression like
CompatibilityActivity = new Activity[1]; // or any other positve number if size is bigger
Activity[] CompatibleActivity = new Activity[size];
// put some element in it like
CompatibleActivity[0]=new CompatibleActivity();

Categories

Resources