Handling null objects in an array - java

I have an array with 18 objects in it, and the array is allocated to have 25 objects in it (the remaining 7 objects are null for future use). I’m writing a program that prints out all the non-null objects, but I’m running in to a NullPointerException and I can’t figure out how to get around it.
When I try this, the program crashes with Exception in thread "main" java.lang.NullPointerException:
for(int x = 0; x < inArray.length; x++)
{
if(inArray[x].getFirstName() != null)//Here we make sure a specific value is not null
{
writer.write(inArray[x].toString());
writer.newLine();
}
}
And when I try this, the program runs, but still prints the nulls:
for(int x = 0; x < inArray.length; x++)
{
if(inArray[x] != null)//Here we make sure the whole object is not null
{
writer.write(inArray[x].toString());
writer.newLine();
}
}
Can anyone point me in the right direction for handling null objects in an array? All help is appreciated!

your check should be:
if(inArray[x] != null && inArray[x].getFirstName() != null)

Related

Reading a text file into an array and performing a sort in Java

I have a homework question I need help with
We have been given a text file containing one word per line, of a story.
We need to read this file into an array, perform a sort on the array and then perform a binary search.
The task also says I'll need to use an overload method, but I'm unsure where
I have a bubble sort, that I've tested on a small array of characters which works
public static void bubbleV1String(String[]numbers)
{
for(int i = 0; i < numbers.length-1; i++)
{
for(int j = 0; j < numbers.length-1; j++)
{
if(numbers[j] .compareTo(numbers[j+1])>0)
{
String temp = numbers[j+1];
numbers[j+1] = numbers[j];
numbers[j] = temp;
}
}
}
}`
And my binary search which I've tested on the same small array
public static String binarySearch(int[] numbers, int wanted)
{
ArrayUtilities.bucketSort(numbers);
int left = 0;
int right = numbers.length-1;
while(left <= right)
{
int middle = (left+right)/2;
if (numbers[middle] == wanted)
{
return (wanted + " was found at position " + middle);
}
else if(numbers[middle] > wanted)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return wanted + " was not found";
}
Here is my code in an app class to read in a file and sort it
String[] myArray = new String[100000];
int index = 0;
File text = new File("threebears.txt");
try {
Scanner scan = new Scanner(text);
while(scan.hasNextLine() && index < 100000)
{
myArray[index] = scan.nextLine();
index++;
}
scan.close();
} catch (IOException e) {
System.out.println("Problem with file");
e.printStackTrace();
}
ArrayUtilities.bubbleV1String(myArray);
try {
FileWriter outFile = new FileWriter("sorted1.txt");
PrintWriter out = new PrintWriter(outFile);
for(String item : myArray)
{
out.println(item);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
When I go to run the code, I get a null pointer exception and the following message
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.compareTo(Unknown Source)
at parrayutilities.ArrayUtilities.bubbleV1String(ArrayUtilities.java:129)
at parrayutilities.binarySearchApp.main(binarySearchApp.java:32)
Line 129 refers to this line of code of my bubblesort
if(numbers[j] .compareTo(numbers[j+1])>0)
And line 32 refers to the piece of code where I call the bubblesort
ArrayUtilities.bubbleV1String(myArray);
Does anyone know why I'm getting a null pointer exception when I've tested the bubblesort on a small string array? I'm thinking possibly something to do with the overloaded method mentioned earlier but I'm not sure
Thanks
You are creating an array of length 100000 and fill the lines as they are read. Initially all elements will be null and after reading the file quite a number of them is likely to still be null. Thus when you sort the array numbers[j] will eventually be a null element and thus calling compareTo(...) on that will throw a NullPointerException.
To fix that you need to know where in the array the non-null part ends. You are already tracking the number of read lines in index so after reading the file that would be the index of the first null element.
Now you basically have 2 options:
Pass index to bubbleV1String() and do for(int i = 0; i < index-1; i++) etc.
Make a copy of the array after reading the lines and before sorting it:
String[] copy = new String[index];
StringSystem.arrayCopy(myArray,0,copy,0,index);
//optional but it can make the rest of the code easier to handle: replace myArray with copy
myArray = copy;
Finally you could also use a List<String> which would be better than using arrays but I assume that's covered by a future lesson.
It seems that you have some null values in your numbers array. Try to debug your code (or just print array's content) and verify what you have there. Hard to tell anything not knowing what is in your input file.
Method overloading is when multiple functions have the same name but different parameters.
e.g. (taken from wikipedia - function overloading)
// volume of a cube
int volume(const int s)
{
return s*s*s;
}
// volume of a cylinder
double volume(const double r, const int h)
{
return 3.1415926*r*r*static_cast<double>(h);
}
Regarding your null pointer exception, you've created an array of size 100000, but it's likely you haven't read in enough information to fill that size. Therefore some of the array is empty when you try to access it. There are multiple ways you can go about this, off the top of my head that includes array lists, dynamic arrays or even moving the contents of the array to another one, once you know the size of the contents (however this is inefficient).

In an array with null spaces, how can consolidate all of the non null values together?

Hey so I have this homework assignment and I'm having issues with one of the methods. I would like hints and not actual answers/code.
So I have a class called HorseBarn that messes with an array of horses(horse being the type). My problem is I'm having troubles with the consolidate method.
What the array would look like before consolidate:
a,b,c,d are horses
|a|null|b|null|c|d|
What the array would look like after consolidate:
|a|b|c|d|null|null|
So my logic would be to make a nested for loop. The first loop would search for a null value, once the first loop finds the null value, the second loop would look for a horse and then swap with it. Then the second loop would end and go back to the first loop. So here is what I have right now and it doesn't work(it just terminates). Is my logic wrong or is it my syntax that's causing the problems?
public void consolidate()
{
int j = 0;
for(int i = 0; i < spaces.length;i++)
{
if( spaces[i] == null)
{
for(j = i; j < spaces.length && spaces[j] == null; j++)
{
}
spaces[i] = spaces[j];
spaces[j] = null;
}
}
Well for starters, this should give an index out of bounds exception if the last non-null is found and there still are elements remaining:
ex: horses = | a | null | null | null |
for i = 1, since horses[1] -> horses[3] are empty, j first gets set to 1 then ends with j = 4 (because of the termination condition j < horses.length())
You would then try to swap horses[1] with horses[4], which throws the array index out of bounds
In the inner for loop, just find the position of next non null value and break it there.
Then swap it with your null.
A better time efficient code.

Break statement doesn't work

This is a small part of my code. Here the break statement doesn't work. The if condition is executed but the break statement takes the control to the start of the while loop. "assign" and "clsAssign" are two array list. "clustersRefGlobal()" is a function and I don't want to pass "assign" when it is empty. However due to break not working it is called even when "assign" is empty. I am not sure why break statement doesn't stop the while loop
Wh:while (i < n) {
System.out.println("Start");
get = clustersRefGlobal(assign);
clsAssign.add(get.get(0));
assign = get.get(1);
if(assign.isEmpty()){
System.out.println("Inside");
break Wh;
}
System.out.println("End");
i++;
}
Here is the output
Start
End
Start
Inside
Start
Exception in thread "main" java.lang.NullPointerException
at softwareClustering.DominantSetClustering.clustersRefGlobal(DominantSetClustering.java:54)
at softwareClustering.DominantSetClustering.buildDominatSetClustering(DominantSetClustering.java:76)
at trees.PrototypeSelectionTree.clustersRefLocal(PrototypeSelectionTree.java:214)
at trees.PrototypeSelectionTree.clustersRefGlobal(PrototypeSelectionTree.java:180)
at trees.PrototypeSelectionTree.buildTree(PrototypeSelectionTree.java:59)
at trees.PrototypeSelectionTree.buildClassifier(PrototypeSelectionTree.java:235)
at weka.classifiers.Evaluation.crossValidateModel(Evaluation.java:617)
at trees.TestClassifier.main(TestClassifier.java:45)
Java Result: 1
The exception is because the "clustersRefLocal()" function is called with empty "assign" parameter. If any one knows whats the problem or what I am missing?
public double[] buildDominatSetClustering(int n) throws Exception {
int i = 1;
ArrayList<ArrayList<Integer>> clsAssign = new ArrayList<>();
ArrayList<Integer> assign = new ArrayList<>();
ArrayList<ArrayList<Integer>> get;
for (int j = 0; j < data.numInstances(); j++) {
assign.add(j);
}
Wh:
while (i < n) {
System.out.println("hello");
get = clustersRefGlobal(assign);
clsAssign.add(get.get(0));
assign = get.get(1);
if(assign.isEmpty()){
System.out.println("inside "+assign.size());
break Wh;
}
System.out.println(assign.size());
i++;
}
if(!assign.isEmpty())
clsAssign.add(assign);
double[] indexAssToClus = new double[data.numInstances()];
int count = 0;
for (ArrayList<Integer> a : clsAssign) {
for (int k = 0; k < a.size(); k++) {
indexAssToClus[a.get(k)] = count;
}
count++;
}
return indexAssToClus;
}
This is the function in which the code exist
The simple explanation to what you are seeing is that in fact the break is stopping the loop ... but the code around the snippet you have shown us is starting it again.
This will be apparent if you add a traceprint immediately before the labelled while statement.
The exception is because the "clustersRefLocal()" function is called with empty "assign" parameter.
I suspect that you are confusing "empty" with null. An empty string is a non-null String that has zero length. If you try to test if a null String is empty by calling String.isEmpty() you will get an NPE. The correct test for a non-null, non-empty String is this:
if (assign == null || assign.isEmpty()) {
// null or empty ... bail out
break;
}
I recommend you simply reverse the logic:
if(! assign.isEmpty()){
i++;
}
But failing that, check what is happening to your variable i:
Your check is for: while (i < n)
But the only place i is ever changed, it is incremented.
labeling your loops and using break label is discouraged. (its like the goto and causes spaghetti code.)
Besides, it's not making sense here, since you don't have nested loops. You can just change break Wh; to break;

Checking Left/Right in an int array for Tetris, Android/Java

I'm trying to make a tetris game for android to help learn game programming for android. My goLeft/Rights break right when the button is pressed, the code for going left is in a class separate of the fields int array, and the list parts array. The fields array is accessed by a referenced variable (TetrisWorld tetrisworld;). While part list array is public so accessed through a variable(part) code for which is in the goLeft() code. It breaks at: if(tetrisworld.fields[x][part.y] != 0) Code for left:
public void goLeft() {
int x = 0;
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
x = part.x - 1;
if(tetrisworld.fields[x][part.y] != 0) {
noleft = true;
break;
}
}
if(noleft == false) {
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
part.x--;
}
}
}
The code for the fields int array:
int fields[][] = new int[WORLD_WIDTH][WORLD_HEIGHT];
WORLD_WIDTH and WORLD_HEIGHT are both static final ints, width being 9 and height being 19
I've tried putting if(tetrisworld.fields[0][0] == 0) and it still crashes so I don't think it has to do with the variables. Also It doesn't go out of bound even if I haven't added the code to check for that yet because I have the teroid spawning around x = 5 and since I can't go left/right once there's not a chance of that happening
I've tried moving the goLeft/Right methods to the gamescreen class which has a "world = TetrisWorld();" and it still bugs out at the same spot
UPDATE:
Ok just adding:
tetrisworld != null
to the first if statement fixed it, my question now is, why did it fix it? Why can't I move without this check? It clearly isn't null cause as far as I know; it's fully responsive now.
But an easier way to have solved this which is SOOOO easy is changing fields to static... then access it lika so: TetrisWorld.fields so my updated code is:
public void goLeft()
{
noleft = false;
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
if (part.x - 1 < 0 || TetrisWorld.fields[part.x - 1][part.y] != 0)
{
noleft = true;
break;
}
}
if (noleft == false)
{
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
part.x--;
}
}
}
Looks like you are hitting IndexOutOfBoundsException.
When you are doing x = part.x - 1;, your x variable can become lesser tan zero, thus your code will act like if(tetrisworld.fields[-1][part.y] != 0
It looks like you're getting a java.lang.NullPointerException when trying to access the array in tetrisworld. In the line you mention there are several ways that this could occur:
if(tetrisworld.fields[x][part.y] != 0) {
tetrisworld could be null.
The fields member of tetrisworld could be null.
The second array that you're looking up by using tetrisworld.fields[x].
The value of part could be null.
Having a quick look through your source code it looks to me like you never initialise tetrisworld, either at declaration using:
TetrisWorld tetrisworld = new TetrisWorld();
Or at some other point which is certain to have happened before your goLeft() method is called.
Ok I believe I found the answer, referencing: http://en.wikipedia.org/wiki/Null_Object_pattern
Apparently java will throw an NPE if you don't check for it first if you have a null reference? Is there any way to initialize it without doing a TetrisWorld tetrisworld = new TetrisWorld(); because it's already created in a different class so i get a thousand errors, an actual stack overflow! lul... Still not 100% positive. Please comment to verify and possibly suggest a better way to go about this.

Help with java array nullpointerexception

I keep receiving a NullPointerException while trying to get a string from any array (that is encapsulated within a Vector). I cannot seem to stop the error from happening. It's got to be something simple, however I think that I have been looking at it for too long and I could sure use another set of eyes. Here is my code:
Vector<Event> details = vector.get(i).getEvent();
for (int x = 0; x < details.size(); x++) {
Event eDetails = details.get(x);
person = eDetails.getEventPerson();
place = eDetails.getEventPlace()[0];
time = eDetails.getEventTime()[0];
}
So when I try to get the item at position 0 in the array (when x is 0) that is returned from eDetails.getEventTime, a NullPointerException is thrown.
Now, when x is 0 I happen to know that the array element at position 0 of the getEventTime() array is an empty string, but it is NOT a null value. When x is 1 or 2, etc. I can retrieve the time just fine.
The problem is that I will still receive the NullPointerException when I try to do things like the following:
**System.out.println(eDetails.getEventTime.length);**
or
String result;
**if(eDetails.getEventTime[0] == null){**
result = "";
} else {
result = eDetails.getEventTime[0];
}
Any ideas?
Thanks!
Are you sure in your second example, it shouldn't be:
if(eDetails.getEventTime() == null)
Instead of:
if(eDetails.getEventTime[0] == null)
Are you making sure you leave the [0] off when you do the null check?
If the function eDetails.getEventTime() returns null, then you'll get a NullPointerException when you try to do eDetails.getEventTime()[0];
Seems that when you get details.get(0).getEventTime() the array returned is null.
The simplest way to figure this out is:
Vector<Event> details = vector.get(i).getEvent();
for (int x = 0; x < details.size(); x++) {
Event eDetails = details.get(x);
if (eDetails == null) {
throw new NullPointerException("eDetails on pos " + x + " is null");
}
person = eDetails.getEventPerson();
Something[] places = Details.getEventPlace();
if (places == null) {
throw ....
}
place = eDetails.getEventPlace()[0];
Something[] times = eDetails.getEventTime();
if (times == null) {
throw ....
}
time = eDetails.getEventTime()[0];
}
It may not look nice but at least it's informative.

Categories