I can't set value of enum in class - java

When I try to pass enum variable as argument to the class this way:
MyClass newObjectMyClass = new MyClass(EnumArgument.AAA);
and then I try to set this argument value as new variable or pass it to next class:
public class MyClass {
EnumArgument xarg;
public MyClass(EnumArgument qarg) {
xarg = qarg;
}
EnumArgument new = xarg;
NextClass nextClassObject = new NextClassObject(xarg);
public void move(Canvas can) {
Log.i("info", "xarg = " + xarg + " nextClassObject.doSomething = " + nextClassObject.doSomething + " new = " + new);
nextClassObject.doSomething(can);
}
}
Logcat show me something like that:
I/info:﹕ xarg = AAA nextClassObject.doSomething = null new = null
threadid=1: thread exiting with uncaught exception
As you see, logcat shows me my "xarg" value well, but "new" variable as null... "new" should have same value as xarg, I'm right?
(I just write this code to show you what I mean, if there is any error it is just probably my mistake.)
I think there is some logical error.
When I put this line:
NextClass nextClassObject = new NextClassObject(xarg);
to my move method it works well.

In Java, initializers are invoked before constructors.
So when you call new Myclass(EnumArgument.AAA), memory is allocated. First, all the fields get default values. So it is as if these instructions were performed:
xarg = null;
new = null; // The name "new" is actually illegal
nextClassObject = null;
That's because the default value for reference variables is null.
The next stage is to calculate and assign the initializers. You have two initializers:
EnumArgument new = xarg;
NextClass nextClassObject = new NextClassObject(xarg);
So you assign the value of xarg to new. But from the previous stage, xarg is null, so new is also null now. nextClassObject receives a new, non-null object reference - but the argument to the constructor of NextClassObject is null!
Then the constructor is called.
public MyClass(EnumArgument qarg) {
xarg = qarg;
}
So now you put the value of your argument - EnumArgument.AAA - in xarg. So the value of xarg is AAA, but the value of new is null, because it was set up in the previous stage, before the constructor assigned the value to xarg.
If you want new to contain the value from the argument, you are not supposed to initialize it with an initializer, but assign a value to it in the constructor:
public MyClass(EnumArgument qarg) {
xarg = qarg;
new = xarg;
}
It would be better if you keep all the field declarations strictly before the constructors and methods. That way you won't be confused about the order of execution.

Related

null pointer exception when initializing a null value items

I want to give value to each of the sub items of a class called State while I have a an array of States initially all null, I am receiving null pointer reference here :
//finding all the neighbor states of a given configuration
public State[] neighborStates(String config, int modeFlag){
State[] neighborStates=new State[7];
int i=0;
for (Operation o : Operation.values()){
neighborStates[i].config=move(config,o.name().charAt(0));
neighborStates[i].realCost++;
neighborStates[i].opSequence+=o.name();
neighborStates[i].heuristicCost=getHeuristicCost(neighborStates[i].config, modeFlag);
i++;
}
return neighborStates;
}
I changed the code to this but I yet get NPE:
public State[] neighborStates(String config, int modeFlag){
State[] neighborStates=new State[8];
int i=0;
for (Operation o : Operation.values()){
neighborStates[i] = new State(move(config,o.name().charAt(0)),neighborStates[i].realCost++,
getHeuristicCost(neighborStates[i].config, modeFlag), neighborStates[i].opSequence+=o.name());
//neighborStates[i].config=move(config,o.name().charAt(0));
//neighborStates[i].realCost++;
//neighborStates[i].opSequence+=o.name();
//neighborStates[i].heuristicCost=getHeuristicCost(neighborStates[i].config, modeFlag);
i++;
}
class State is defined as:
public class State {
public State(String config, int realCost, int heuristicCost, String opSequence){
this.config = config;
this.realCost = realCost;
this.heuristicCost = heuristicCost;
this.opSequence = opSequence;
}
You need to instantiate State(s) in your neighborStates array. You have created an array with 7 slots, but they're all initially null. Assuming you have a default constructor, it should look something like,
for (Operation o : Operation.values()){
neighborStates[i] = new State();
// ...
Also, it's probably a good idea to size neighborStates based on Operation.values()
State[] neighborStates = new State[Operation.values().length];
When you create an array of a specified size as you do with
State[] neighborStates = new State[7] you allocate that memory. Each index of the array is initialized with whatever the default value for the type is. The default value for booleans is false. The default value for numbers is 0. Here's the part that matters: the default value for references is null.
All of the values in the array will be null until you instantiate them with, say neighborState[i] = new State();
When you write this line of code
State[] neighborStates=new State[7];
You just receive a refrence to a Array Object, with all of 7 item inside is null, this line only initialize the State Array object, without any items inside.
So in the for loop, all item is still null, you have to initialize each item first befor using it.
neighborStates[i] = new State();
For the version of your question after the update.
You are evaluating this expression -
new State(move(config,o.name().charAt(0)),neighborStates[i].realCost++,
getHeuristicCost(neighborStates[i].config, modeFlag), neighborStates[i].opSequence+=o.name());
before you have assigned a value to neighborStates[i]. So the part that says neighborStates[i].realCost++ is triggering the null pointer exception - neighborStates[i] is still null.
You only init an array , but you have not constructed the member in State[] array.
You need to call constructor to construct the State class before you use it.
Try to change your code like this:
public State[] neighborStates(String config, int modeFlag){
State[] neighborStates=new State[7];
int i=0;
for (Operation o : Operation.values()){
neighborStates[i] = new State(move(config,o.name().charAt(0)),
someRealCost, //what's the value of this parameter?
getHeuristicCost(config, modeFlag),
modeFlag
);
....
i++;
}
}

What happens when result of new Class() is not assigned to a variable

I came across this code that says
new Class_Name(); // (i)
Now, normally I see the result of the new statement assigned to a variable:
Class_Name n = new Class_Name();
And n reference to the object created. What really happens when the (i) is called? And why would anyone want to do it? What are the uses for it?
CODE
class Tree {
int height;
Tree() {
print("Planting a seedling");
height = 0;
}
Tree(int initialHeight) {
height = initialHeight;
print("Creating new Tree that is " +
height + " feet tall");
}
void info() {
print("Tree is " + height + " feet tall");
}
void info(String s) {
print(s + ": Tree is " + height + " feet tall");
}
}
enter code here
public class Overloading {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
Tree t = new Tree(i);
t.info();
t.info("overloaded method");
}
// Overloaded constructor:
new Tree();
}
}
What really happens when the (i) is called
The below line of code creates an object of type Class_Name and since it is not referred by any reference variable , it dies immediately.
new Class_Name();
This way you can create an object of that class , and invoke methods on it without assigning it to a reference. This you will do when you need that object only once in your code and don't want to unnecessarily keep a reference to it . The anonymous object is created and dies instantaneously. This is quick and dirty :
new Class_Name().someMethod();
In I/O streams and AWT, we use many objects only once in the program; for them, better go for anonymous objects as follows.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After the Edit:
new Tree();
Your intention here was to execute the code in the constructor .But your code won't compile I believe you need to put the last line inside some method.
new Class_Name();
This statement will create the object of Class_Name and constructor will be called but you are not holding the refernece of that class, so you can not call any other method. Here this Object scope will be limited where it has written, say in method or block.
A general use of it. new Thread(new RunnableTest()).start();
class RunnableTest implements Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println("i : "+i);
}
}
}
new class_name() will create object of class_name.As you are not storing reference of it ,you will not be able to use same object in the code after this statement.But it's good practice to store the reference of object if you want to use it later in code.Which will help you to reduce efforts in managing multiple objects and memory too.
when you want to use oop you must create lots of class with a lots of attribute
and sometimes you need to use a attribute of some class in a specific class so you need to
create a object of those class by using
new Class_Name();

java arraylist overwrites existing elements

I seem to have a frustrating problem - an element of my arraylist is overwritten. I have looked at many posts in many forums, but I have not managed to solve it. :chomp:
In my program (which is actually a FBDK function block algorithm implemented in Java), I want to store the data of an input variable (PART) into an element of an out variable array (PART_array). This process will happen multiple times (with the occurence of an event) and must thus store the variable in several array elements.
The problem is that the elements of PART_array are overwritten by the last entry. For instance, for the first event occurence, PART_array[] = ["1"," "," "," "," "," "]. Then, with the second occurence, instead of PART_array[] = ["1","2"," "," "," "," "], I find PART_array[] = ["2","2"," "," "," "," "] - thus showing the overwrite. I have realised that overwrite already occurs with the storage to PART_ARRAY ArrayList. I thought that by reinitializing (p = new Part()) the problem would be solved...obviously not.
Any help in solving this problem will be GREATLY appreciated! The code is as follows:
public class STORE_TO_ARRAY extends fb.rt.FBInstance {
public ArrayList<Part> PART_ARRAY = new ArrayList<Part>();
Part p = new Part();
/** The default constructor. */
public STORE_TO_ARRAY() {
super();
}
/** ALGORITHM REQ IN Java*/ -- a method called in the program
public void alg_REQ() {
int ct = 0;
ct = current_task;
if (ct <= NumOfTasks) {
//write received input data to output variable array elements
//this is where the problem occurs!!!!
p.setPart(PART); //set value of Part
PART_ARRAY.add(ct-1,p); //adding to arraylist
Part p = new Part(); //trying to reinitialise the object
}
}
}
The class file for Part is as follows:
public class Part {
WSTRING part;
void setPart(WSTRING part) {
this.part = part;
}
WSTRING getPart() {
return part;
}
}
The below code creates a local variable (which, in the following line, goes out of scope and disappears before it is used), rather than assigning the class variable with a new value (which I'm assuming is what you're trying to do).
Part p = new Part(); //trying to reinitialise the object
Try replacing it with
p = new Part(); //trying to reinitialise the object
On a side note, a decent IDE (like NetBeans) should give you a warning about creating a local variable which hides a class variable.

Having trouble with accessing array data from one class to another

I am having some trouble with passing data of an array from one class to the next.
edits
I am now no longer getting the error, and my code compiles, but as I had been warned, I got null for every element of the array. Now that I have taken out the static modifiers though, it still gives me null. I have also updated the code.
Here is the class where the array is created.
public class AssignSeat {
String[] arrangement = new String[12];
public void SeatStart() {
arrangement[0] = "Collins";
arrangement[2] = "Faivre";
arrangement[3] = "Kinnard";
arrangement[6] = "Morgans";
arrangement[7] = "Rohan";
arrangement[8] = "Shatrov";
arrangement[9] = "Sword";
arrangement[11] = "Tuckness";
System.out.format("%-15s%-15s%n", "seat", "passenger");
for (int i=0; i<arrangement.length; i++) {
System.out.format("%-15s%-15s%n", i+1, arrangement[i]);
}
}
public String[] getArrangement() {
return arrangement;
}
public void setArrangement(String[] arrangement) {
this.arrangement = arrangement;
}
}
and here is the method trying to access the information. It is specifically the for loop that I need help with so Ignore other areas where there are mistakes. Thank you.
public void actionPerformed(ActionEvent event) {
Scanner scanner = new Scanner(System.in);
AssignSeat seat = new AssignSeat();
if(event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("first class")) {
entername.setVisible(true);
seatnum.setVisible(true);
confirmed.setVisible(true);
inputline.setVisible(true);
outputline.setVisible(true);
if ((seat.arrangement[1] == null)) {
System.out.println(seat.arrangement[0]);
System.out.println(seat.arrangement[2]);
two.setForeground(Color.green);
}
} else if (buttonText.equals("coach")) {
//System.out.println("so does this!");
entername.setVisible(true);
seatnum.setVisible(true);
confirmed.setVisible(true);
inputline.setVisible(true);
outputline.setVisible(true);
if ((seat.arrangement[4] == null)) {
five.setForeground(Color.green);
}
if ((seat.arrangement[5] == null)) {
six.setForeground(Color.green);
}
if ((seat.arrangement[10] == null)) {
eleven.setForeground(Color.green);
}
}
}
}
The problem lies in the fact that the array was declared as static, but the initialization code for it is in the constructor. Remove all the static modifiers in the original code, and replace this part:
if (AssignSeat.getArrangement()[1].equals("null"))
With this:
AssignSeat assign = new AssignSeat();
if (assign.getArrangement()[1] == null)
Also notice that "null" is not a null value, use null (without quotes) for that.
A different approach would be to leave the array as an static member, but initialize it statically, like this:
private static String[] arrangement = new String[12];
static {
arrangement[0] = "Collins";
arrangement[2] = "Faivre";
arrangement[3] = "Kinnard";
arrangement[6] = "Morgans";
arrangement[7] = "Rohan";
arrangement[8] = "Shatrov";
arrangement[9] = "Sword";
arrangement[11] = "Tuckness";
}
In that case, this would work:
if (AssignSeat.getArrangement()[1] == null)
But I still believe that making the array static is going to be problematic if several instances of the class happen to be modifying its contents.
Replace
if (AssignSeat.getArrangement()[1].equals("null"))
with
if (AssignSeat.getArrangement()[1] == null)
If the value is null, you can't invoke methods (like equals) on it. You need to compare the value directly to null, which is a constant rather than a string.
Ok, I'm a bit confused as to what you're trying to do in the first class. You are initializing a static array from an instance method...
In other words, the String values in the array will be null until you call SeatStart from an instance of the class.
Try to initialize the String array from the static constructor for AssignSeat to make sure it has been initialized before you use it: http://www.snippetit.com/2009/05/java-static-variables-static-methods-and-static-constructor/
You are trying to use an attribute of a class, without instantiating the object first. Until you call a default/user-defined constructor, there is no memory dedicated to the attribute of that object.
Even though you manage to call the method you are using a static method, which can be called without an instance of the object being required.
Create a constructor for the object (or use a default constructor) and then you will be able to access your attribute because your object will be on the heap and have memory allocated for the string[].
Simply define the SeaStart as an Array.
public String[] SeatStart() {
arrangement[0] = "Collins";
arrangement[2] = "Faivre";
arrangement[3] = "Kinnard";
return arrangement;
}
For convinience, make a new array to copy the array from AssignSeat class. Then retrieve the value from that array.
public void actionPerformed(ActionEvent event) {
AssignSeat seat = new AssignSeat();
String[] foo = seat.SeatStart();
System.out.println(foo[0]);
System.out.println(foo[1]);
System.out.println(foo[2]);
}
Though you can acces it also with:
System.out.println(seat.SeatStart()[0]);
The result would be:
Collins
null
Faivre
and that 'null' is because apparently you haven't allocate a value for arrangement[1] :-)
But in the end, it works.

Java: Copy Constructor not going as planned

I have a bit of a problem. I'm making a Finite Automata checker.
Given an input, and the DFA, does it end on a accepting state.
My problem is creating a new DFA_State from another's target.
DFA_State state0, state1, curr_state, init_state, temp; //fine, I think
state0 = new DFA_State();
state1 = new DFA_State();
state0 = new DFA_State("State 0",true, state0, state1); //fine, I think
init_state = new DFA_State(state0); //fine, I think
but, this bit is throwing up problems.
temp = new DFA_State(curr_state.nextState(arr1[i]));
*
*
curr_state = new DFA_State(temp);
Thanks for any help,
Dave
Edit:
God I was retarded when I did this, AFAIK, I just wasn't thinking straight, added methods to set the values to the DFA_State object.
//in DFA_State class
public void set(DFA_State on_0, DFA_State on_1, Boolean is_accepting, String name){
this.on_0 = on_0;
this.on_1 = on_1;
this.is_accepting = is_accepting;
this.name = name;
}
//in main
DFA_State state0, state1, curr_state;
state0 = new DFA_State();
state1 = new DFA_State();
state0.set(state0, state1, false, "State 0");
state1.set(state1, state0, true, "State 1");
curr_state = state0;//initial state
//iterate across string input changing curr_state depending on char c
curr_state = getNextState(c);
//at end
if(curr_state.isAccepting())
System.out.println("Valid, " + curr_state.getName() + " is accepting);
else
System.out.println("Invalid, " + curr_state.getName() + " is not accepting);
In that first line, you declare the variables state0, state1, curr_state, init_state and temp as being variables of type DFA_State. However, that only declares them, they are not yet initialized. The next few lines are all okay. Second line creates a state without anything in it and assigns it to state0, so does the third line for state1. Fourth line overwrites your previous state0 assignment with a new DFA_State that has actual contents. Fifth line creates a DFA_State as a copy of state0 and assigns it to init_state.
Assuming there's nothing in between this and the first line of your second code block, now you'll get a problem. You're assigning temp with a new DFA_State that uses a copy-constructor with an argument relying on curr_state. But at that point, that variable hasn't been initialized yet. Just because it was declared doesn't mean it has somehow already been structured in memory. When you call nextState on it, there's simply no variable to resolve this to. Don't expect to get something like a pointer that will eventually point to a part of what you put in curr_state.
I'm just guessing, but from your code style I'd say you have a background in C or C++. Look into the differences between those languages and Java. If possible, I'd also advise you to make your DFA_State class immutable, since this is more reliable and will avoid mistakes. That means getting rid of the no-args constructor. Here's a reworking of it (not actually compiled, might contain errors):
package foundations.of.computing;
/**
*
* #author Kayotic
*/
class DFA_State {
private final String state;
private final DFA_State on_0;
private final DFA_State on_1;
private final boolean isAccepting;
//private DFA_State dummy;
public DFA_State(DFA_State arg) {
//this(arg.is_accepting(), arg.on0(), arg.on1());
state = arg.get_name();
isAccepting = arg.is_accepting();
on_0 = arg.on0();
on_1 = arg.on1();
}
public DFA_State(String name, Boolean accepting, DFA_State on0, DFA_State on1) {
state = name;
isAccepting = accepting;
on_0 = on0;
on_1 = on1;
}
public String get_name(){
return state;
}
public Boolean is_accepting() {
return isAccepting;
}
public DFA_State on0() {
return on_0;
}
public DFA_State on1() {
return on_1;
}
public DFA_State nextState(char i) {
if (i == '0') {
return on0();
} else if (i == '1') {
return on1();
} else {
System.out.println("Error with input");
return null;
}
}
}
Even if you can't make the instance variables final, it's best to at least make them private, since you already have methods for getting them.
There are better memory representations of DFAs than the object-oriented.
You should use a simple lookuptable:
int[] table = new int[vocabularyCount][stateCount];
Every State and every word gets a number, starting with 0.
Fill the table with the state transitions, or -1, if there is no transition. Now you just need the translation methods for the states and the words.
Heres a generic DFA algorithm:
public boolean checkSentence(String s, int[] finishes) {
// fill table
int state = 0; // assuming S0 is the start state
for (int i = 0; i < s.length(); i++) {
state = table[translate(s.charAt(i))][s];
}
for (int i = 0; i < finishes.length; i++) {
if (finishes[i] == state) {
return true;
}
}
return false;
}
The program is quite poorly written. Look at this in your FoundationsOfComputing.java:
state0 = new DFA_State();
state1 = new DFA_State();
state0 = new DFA_State("State 0",true, state0, state1);
You essentially created 3 instances of state - two instances which are not initialized (first two lines in your code) - all their instance variables are null.
Then you create the third instance, which you point to the first two uninitialized ones, and assign it to state0 variable. Please note, at this point, it is only the value of the variable that changes, not the values you passed in the DFA-State constructor!!! So, what you now have in state0 is a state that points to two uninitialized states.
Now let's look at the code further down in the FoundationsOfComputing.java:
while (i < arr1.length) {//loops through array
System.out.println(i + ". scan shows " + arr1[i]);
temp = new DFA_State(curr_state.nextState(arr1[i]));
System.out.println(" "+curr_state.get_name()+ " moves onto " + temp.get_name());
curr_state = new DFA_State(temp);
i++;
}
I am guessing this throws NullPointerException - that code moves to the on_0 state of state0 - which is a state that has not been initialized (all it's instance variables are null), so in the following pass of the loop, when it calls curr_state.nextState(whatever), it would return null and you are trying to pass that to the copy-constructor which would result in NPE.
Ok so we know this is homework. Let's do this instead of telling you the answer let's try and work through it on your own. If you are seeing a NullPointerException (NPE). Grab the second line of the exception:
java.lang.NullPointerException: null
at com.blah.blah.SomeObject.someMethod(SomeArgumentType):1234 <<< here
....
That 1234 is the line number in the file that contains SomeObject. If you goto that line number you can see exactly where the NPE is being generated from. For example if line 1234 was:
this.foo = bar.indexOf("caramel");
You can easily deduce what was null. No clue? Well this can never be null so this.foo isn't the problem. If this could be null you couldn't be inside that method because this points to the instance you are currently within. Therefore, the only other statement where a variable is being dereferenced is bar so bar must be null. Let's look at your code:
temp = new DFA_State(curr_state.nextState(arr1[i]));
Say you find out the line above is tossing an exception. Well there could be several things that could be null. curr_state could be null, or arr1 could be null in which case this line would blow up. However, if arr1[i] is null or curr_state.nextState() is returning null then you won't see the NPE pointing at this line, but would be coming out of the constructor should someone try to call methods on that method parameter.
Hopefully, this will give you the tools you need to track down problems in your application by understanding exception stack traces.

Categories