Reputation: 73
Why is this giving me the error of Nullpointerexception? It is happening on the 3rd line of my code, so my first for loop. Just so you know, this is a method with access to other parts of a larger code.
public static void insertionsort()
{
for (int outer = 1; outer < array.length; outer++)//Outer=next number to be sorted
{
String temp = array[outer]; //Stores it for later use
int inner = outer; // inner used to track shifts
while (inner > 0 && array[inner - 1].compareTo(temp) >= 0)
{
array[inner] = array[inner - 1];//Swaps the number
inner--;// Decrements
} //shift them all right until one is smaller
array[inner] = temp;//Now it will put the stored number into its ordered position.
}
}
Upvotes: 0
Views: 72
Reputation: 1
I just created a unit test to reproduce the NPE, and I didn't get any error. My suggestion is to split the for sentece in multiple lines, so you will get exactly where is the NPE.
for (int outer = 1;
outer < array.length;
outer++)//Outer=next number to be sorted
{
The full unit test is:
package src.test.java;
import org.junit.Test;
public class TestOne {
private static String[] array={"sa","se","si","so", "su"};
@Test
public void TestOne(){
this.insertionsort();
}
public static void insertionsort()
{
for (int outer = 1;
outer < array.length;
outer++)//Outer=next number to be sorted
{
String temp = array[outer]; //Stores it for later use
int inner = outer; // inner used to track shifts
while (inner > 0 && array[inner - 1].compareTo(temp) >= 0)
{
array[inner] = array[inner - 1];//Swaps the number
inner--;// Decrements
} //shift them all right until one is smaller
array[inner] = temp;//Now it will put the stored number into its ordered position.
}
}
}
Upvotes: 0
Reputation: 5637
The variable array
is not defined in this line
for (int outer = 1; outer < array.length; outer++)//Outer=next number to be sorted
If this is a function parameter then add it like this
public static void insertionsort(int[] array)
{
for (int outer = 1; outer < array.length; outer++)//Outer=next number to be sorted
or define it inside
public static void insertionsort()
{
int[] array = {2,1,4,7,6,3};
for (int outer = 1; outer < array.length; outer++)//Outer=next number to be sorted
Upvotes: 2