为什么这会给我Nullpointerexception的错误?它发生在我的代码的第3行,所以我的第一个循环。您知道,这是一种可以访问更大代码的其他部分的方法。
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.
}
}
答案 0 :(得分:2)
此行中未定义变量array
for (int outer = 1; outer < array.length; outer++)//Outer=next number to be sorted
如果这是一个函数参数,那么像这样添加它
public static void insertionsort(int[] array)
{
for (int outer = 1; outer < array.length; outer++)//Outer=next number to be sorted
或在
中定义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
答案 1 :(得分:0)
我刚刚创建了一个单元测试来重现NPE,但我没有收到任何错误。我的建议是将fortetece分成多行,这样你就可以得到NPE的确切位置。
for (int outer = 1;
outer < array.length;
outer++)//Outer=next number to be sorted
{
完整的单元测试是:
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.
}
}
}