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++;
}
}
Related
I'm trying to remove null values from an array, and returning them to do some other stuff with the new values. However, I'm confused about how to get the updated array.
This is the null removal code.
String[] removeNull(String[] nullArray) {
int nullCounter = 0;
//checking if any is null
for(int i = 0; i < nullArray.length; i++) {
if(nullArray[i]==null) {
nullCounter++;
}
}
String[] noNulls = new String[nullArray.length-nullCounter];
if(nullCounter>0) {
//make a non null array
for(int i = 0, j = 0; i <noNulls.length; i++) {
if(nullArray[i]!=null) {
noNulls[j] = nullArray[i];
j++;
}
}
}
return noNulls;
}
I'm pretty sure that is already correct (Please correct me if I'm wrong). Then, I called it inside a constructor.
public theBoundary(String[] bounds){
removeNull(bounds);
}
After I called removeNull(bounds), will the value of the new array be stored in the array bounds? Or will it be stored in the array noNull? I can't seem to find where the new values are stored.
Thank you, and please tell me if there are mistakes. I've been going around this for half an hour now.
Note: If possible, please don't give me answers that include importing something else. Vanilla Java would be preferred.
removeNull() returns the array noNulls, created inside the method. Currently, in theBoundary(), you simply call removeNull(bounds), but do not assign it to a variable. The newly created null-free array is created, not assigned, and immediately garbage collected.
If you wish to do something with your non-null-containing array (which I assume you do), do this:
public theBoundary(String[] bounds) {
String[] withoutNulls = removeNull(bounds);
doSomething(withoutNulls); // whatever you need here
}
Note, unless you really have to use an array, consider using a List or even a Stream.
List example:
List<String> list = ... // from somewhere else
list.removeIf(s -> s == null);
doSomething(list);
Stream example:
Stream<String> stream = ... //from somewhere else
stream.filter(s -> s != null);
doSomething(stream);
EDIT
Even if you do really need arrays, the following will also work:
String[] noNulls = (String[]) Arrays.stream(inputArray).filter(Objects::nonNull).toArray();
I don't think there is any need to iterate the array twice!
You can instead use a stream on array and filter the indexes without that are NOT NULL.
Also, you can do this without needing to create the removeNull method, and do this directly in your theBoundary method.
Here is how your code will look like:
String[] arrayWithoutNull = Arrays.stream(bounds).filter(Objects::nonNull).toArray(String[]::new)
I hope this solves your problem.
Do you mean this?
public theBoundary(String[] bounds){
String[] cleanedBounds = removeNull(bounds);
}
You are not doing it inplace so you need to assign it back to a new array
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.
i have short question, tell me just why first example don't work and second works.
Code before examples:
Tiles[] myTiles = new Tile[23];
number = 1;
First Example:
for(Tile tile : this.myTiles) {
if (number != this.myTiles.length) {
tile = new Tile(number, getResources().getColor(R.color.puzzle_default));
number++;
}
}
Second Example:
for(Tile tile : this.myTiles) {
if (number != this.myTiles.length){
this.myTiles[number-1] = new Tile(number, getResources().getColor(R.color.puzzle_default));
number++;
}
}
If i use code below in other method in class
this.myTiles[0].getNumber();
It's NullPointerException.
But with Second Example it nicely works.
I really don't know why. Thanks for any response
The first loop makes a copy of each object and is equivalent to
for (int i=0; i < myTiles.length; i++) {
Tile tile;
...
tile = new Tile(...); // set local reference only
}
As elements in an Object array are null by default these would remain unassigned outside the scope of the loop. The original elements of the myTiles remain at their default null values
The for each loop uses an Iterator internally to fetch items from the collection and return you a new reference to a local variable containing each element - overwriting this reference is completely useless, as it is only valid for one for-loop and will be replaced on the next.
"Internally", your first loop would translate to
for (Iterator<Tile> iterator = myTiles.iterator(); iterator.hasNext;){
Tile tile = iterator.next();
tile = new Tile(number, getResources().getColor(R.color.puzzle_default));
number++;
}
In Java, there is no such thing as manipulating a pointer directly. Any time you get a reference to an object, you are getting a copy to a reference, like a pointer to a pointer. For this reason if you do something like:
String s = "hello";
modify(s);
System.out.println(s); // still hello!
void modify(String s){
s = s + " world";
}
You can't actually change the original reference s because the function is manipulating a copy to that reference. In the example above you would need something like this:
String s = "hello";
s = modify(s);
System.out.println(s); // prints 'hello world'
String modify(String s){
return s + " world";
}
The same happens in your for comprehension. The variable tile is bound to the loop and is a copy of a reference in the array. The original reference (the array at the given position) can't be changed directly this way. That's why you need to call directly:
myTiles[i] = // something
Read this article for more information.
So the idiomatic way of modifying an array in java is something like:
for(int i = 0; i < myTiles.length; i++){
myTiles[i] = new Tile(...); // directly reassigning the reference in the array!
}
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.
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.