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

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

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

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

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.

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

Strange error with simple code [duplicate]

This question already has answers here:
Java order of Initialization and Instantiation
(2 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When I run this code I get the NullPointerException on line int length = origin.length();
If I run in the debug mode it stoped on the same line but in the variable tab the origin value is as it might be i.e. the value from the main method.
So why is NullPointerException there in runtime?
public static void main(String[] args) {
String regexp = "(?:a)";
Task t = new Task(regexp); // error
t.process();
}
class Task {
private String origin;
public Task() {
}
public Task(String origin) {
this.origin = origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getOrigin() {
return origin;
}
int length = origin.length(); //NullPointerException
...
origin is not initialized when you initialize your length variable. Set it to zero, and initialize origin like this:
private String origin = new String();
or the origin variable will be a null string before it is set through your setter.
And I would replace
int length = origin.length(); //NullPointerException
by
public int get_length() { return origin.length(); }
so length property is always properly correlated to actual origin length.
Because of the lifecycle of Java objects: the length attribute is set before the code in the constructor is executed, so the origin attribute is still null.
Calculate the length in the constructor so solve that issue:
public Task (String o) {
this.origin=o;
this.length=this.origin.length();
}
And then update the setter:
public void setOrigin(String origin) {
this.origin = origin;
this.length=origin.length;
}
Or just create a getter for the length and don't store that value (best option, in my opinion):
int getLength() {
this.origin.length();
}
The instance (and static) variables are initialized right after the (implicit or explicit) call to super(). So this is before you can assign anything to your String origin.
Take care of initializing fields depending on different fields! JVM tries to initialize them before calling the constructor!
public static void main(String[] args) {
String regexp = "(?:a)";
Task t = new Task(regexp); // error
t.process();
}
class Task {
private String origin;
private int length;
public Task() {
//optional - depending on what you like/need
origin = new String();
length = 0;
}
public Task(String origin) {
this.origin = origin;
this.length = origin.length();
}
public void setOrigin(String origin) {
this.origin = origin;
this.length = origin.length();
}
public String getOrigin() {
return origin;
}
...

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.

Categories

Resources