Strange error with simple code [duplicate] - java

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

Related

Why is global object array suddenly null when it enters a method?

Why would a non-null global array suddenly become null in a method?
I have tried to move the method into the object class and access it that way since the getWeight() method works fine, but I have the same issue. As soon as I step into the viablePaths method the global arrays are null. I am using eclipse to toggle breakpoints and I can see everything in the arrays before I step into the method.
I would like the method to be able to access the paths and archs arrays and return an integer value. With the content of the arrays right now the method should set the pathIndex integer variable to -1. I do not know what else to put for the desired behavior. The desired behavior should be for the the global object arrays to not become null when the method is called.
Currently the error I get is a NullPointerException from the line where the determineViable paths method is called.
public class StackHelpProblem {
public static int numEdges;
public static int queries;
public static Edge[] paths;
public static Edge[] archs;
public static void main(String[] args) {
numEdges = 3;
queries = 2;
Edge[] paths = new Edge[numEdges];
paths[0] = new Edge(1);
paths[1] = new Edge(2);
paths[2] = new Edge(3);
Edge[] archs = new Edge[queries];
archs[0] = new Edge(10);
archs[1] = new Edge(10);
int pathIndex = 0;
// Reachable artifacts set
for (int i = 0; i < queries; i++) {
System.out.println(archs[i].getWeight());
pathIndex = determineViablePaths(archs[i].getWeight());
}
}
// Method to return last index of path that can be traversed
public static int determineViablePaths(int weight) {
for (int i = 0; i < numEdges; i++) {
if (paths[i].getWeight() <= weight)
continue;
else {
return i - 1;
}
}
return numEdges-1;
}
// The edge class
public static class Edge implements Comparable<Edge> {
int weight;
Edge(int weight) {
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
// The Edge comparison method
public int compareTo(Edge other) {
if(this.weight < other.weight)
return 0;
else if (this.weight == other.weight)
return 1;
return -1 ;
}
}
}
the getWeight() works and the determineViablePath(int weight) method does not work. As soon as that method is entered the global arrays become null.
Thank you for any assistance.
Let us analyze the relevant parts of the code to understand why the Exception is thrown and how we can prevent it.
public class StackHelpProblem {
...
public static Edge[] paths;
public static Edge[] archs;
...
}
The two static fields Edge[] paths and Edge[] archs are not initialized and thus implicitly initialized with null.
public class StackHelpProblem {
...
public static void main(String[] args) {
...
Edge[] paths = new Edge[numEdges];
...
Edge[] archs = new Edge[queries];
...
}
...
}
In method static void main(...), two new arrays paths and archs are created. Those do not reference the static fields. Thus, the static fields are still initialized with null.
In method static int determineViablePaths(...), no local variable paths is found, thus static field paths is used, which still is null. Thus, the array-access will result in a NullPointerException.
We can get rid of the NullPointerException by using the existing static fields instead of creating new variables in method static void main(...):
public class StackHelpProblem {
...
public static void main(String[] args) {
...
paths = new Edge[numEdges];
...
archs = new Edge[queries];
...
}
...
}
Ideone demo

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

Using private variables [duplicate]

This question already has answers here:
What is the point of setters and getters in java? [duplicate]
(14 answers)
Getter-Setter and private variables [duplicate]
(5 answers)
Closed 8 years ago.
public class Addition
{
private int number1,number2;
public void setNumber1()
{
}
public int getNumber1()
{
}
public void setNumber2()
{
}
public int getNumber2()
{
}
}
what is point of keeping variables private if i can access them using public getter and setter method.
Having a setter method allows you to implement logic prior to assigning a value to the private variable. This prevents other code from assigning arbitrary values to your private variable which might cause your object to be in an invalid state. For example:
Without setter method
public class Man {
public int height;
}
//...some code
man.height = -1; // BOOOM!
With setter method:
public class Man {
private int height;
public void setHeight(int h) {
this.height = h >= 0 ? h : 0;
}
}
//...
man.setHeight(-10); // Will keep the man in valid state
You can add a validation in setters.
private int age;
public void setAge(int a){
if(a>0){
this.age = a;
}else{
this.age = 0;
}
}
You can assume that making a variable as private is a basic guideline for coding. If you make them public it is accessible for outside world and any one can modify it.
Suppose that number1 should always be +ve int in your case. So the setter method will have check and help you to avoid setting -ve values to it. See below:
public void setNumber1(int number)
{
if(number >= 0)
{
this.number1 = number
}
else
{
//you can throw exception here
}
}
It follows a important Object Oriented Property Encapsulation .
For example I have a integer variable price with public modifier(Any one can access it)
public int price;
now we know that price can not negative but it is public so we don't have any control in this. Now see it with respect to encapsulation
private int price;
public void setPrice(int price)
{
if(price>0)
this.price=price
}
Here we have control, no one can set negative value of price. This is the power of Encapsulation "Giving Control".

Logic error possibly misunderstanding in java assignment

I've been having numerous problems getting this project to work correctly but I'm currently stuck on getting this class to work properly. Whats its suppose to do is take the current station from the radio class and pass it along to this class. The problem is i'm trying to select between AM and FM but every time i run it, it only displays the AM station. I don't understand why it automatically gets set to that station.
public class AutoRadioSystem
{
private Radio selectedRadio;
private AMRadio radioAM;
private FMRadio radioFM;
private XMRadio radioXM;
//is this the correct place to initialize these?
Radio amRadio = new AMRadio();
Radio fmRadio = new FMRadio();
public AutoRadioSystem()
{
//even making the selected radio FM still produces values for AM
selectedRadio = radioFM;
}
// this is where my problem currently lies and probably much more. Shouldn't it return 0.0 without any station being selected.
public double getCurrentStation()
{
if (selectedRadio == radioAM)
{
return amRadio.getCurrentStaion();
}
else if (selectedRadio == radioFM)
{
return fmRadio.getCurrentStaion();
}
return 0.0;
}
//I'm not sure if i'm setting this up correctly to switch the radio from am to fm
public void selectRadio()
{
if (selectedRadio == radioAM)
selectedRadio = radioFM;
}
public static void main (String [] args) {
AutoRadioSystem c = new AutoRadioSystem();
c.selectRadio();
double b = c.getCurrentStation();
System.out.println(b);
}
}
public class AMRadio extends Radio
{
private static final double Max_Station = 1605;
private static final double Min_Station = 535;
private static final double Increment = 10;
public AMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("AM " + this.currentStation);
return message;
}
}
public class FMRadio extends Radio
{
private static final double Max_Station = 108.0;
private static final double Min_Station = 88.0;
private static final double Increment = .01;
public FMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("FM " + this.currentStation);
return message;
}
}
public abstract class Radio
{
double currentStation;
RadioSelectionBar radioSelectionBar;
public Radio()
{
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{
}
public void down()
{
}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
this.currentStation = freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
}
The problem is, in .getCurrentStation(), both selectedRadio & radioAM is not init and is null.
The mistake begin with:
public void selectRadio()
{
if (selectedRadio == radioAM)
{
selectedRadio = radioFM;
}
}
Here, the selectedRadio = null, so it's never get assign value.
Edit: I believe you're just begin with this, so a little more details will help.
You make mistake when declare two field, amRadio & radioAM then init one of them and use another.
You didn't set value to selectedRadio and compare it, this always return false
The best place to init value for an instance is the constructor method, here is AutoRadioSystem()
You may want to change the code to like this:
private Radio selectedRadio;
public AutoRadioSystem()
{
selectedRadio = new FMRadio();
}
// To compare, using instanceOf, but better design will use enum value instead, up to you
I think I've found the problem
You have 2 fields for each Radio overload
private AMRadio radioAM;
...
Radio amRadio = new AMRadio();
but the one you're comparing to: radioAM never gets instantiated, and therefore is always null.
When you call
if (selectedRadio == radioAM)
both selectedRadio and radioAM are null, so of course they would be equal
unless you intend radioAM and amRadio to be completely different instances, than you shouldn't have 2 fields like that.
Since you're using polymorphism, you might want to use the latter one
Radio amRadio = new AMRadio();
All properties selectedRadio, radioAM and RadioFM are null. The code in the constructor has no effect because selectedRadio = RadioFM. This means that selectedRadio its value does not change and remains zero.
Therefore selectedRadio == radioAM (null == null) in getCurrentStation is always true.This will always apply the first if-block in your method getCurrentStation and will always return the "amradio".
Caio

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