出于某种原因,我无法使用Strings compareTo方法来工作。我收到此错误消息:
exception in thread main java.lang.NullpointerException
at java.lang.String.compareTo(Unknown Source)
at Sort.main(Sort.java:27)
我该怎么做才能解决这个问题? (此代码要求to arrays数组已经单独排序。)
import java.util.*;
class Sort{
public static void main(String[] args){
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
String[] flettet = new String[ord.length + ordet.length];
for(int i = 0; i < ord.length; i++){
int teller = i;
for(int j = 0; j < ordet.length; j++){
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
teller += 1;
}
}
flettet[teller] = ord[i];
}
}
}
答案 0 :(得分:5)
你的意思是 - 看起来你正在设置错误的数组:
String[] ordet = new String[6];
ordet[0] = "akilles";
ordet[1] = "kopper";
ordet[2] = "lipton";
ordet[3] = "mus";
ordet[4] = "orkester";
ordet[5] = "toving";
答案 1 :(得分:0)
您永远不会为ordet分配任何值。所以compareTo将字符串与NULL进行比较
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles"; //overwriting ord[0]
ord[1] = "kopper"; //overwriting ord[1]
ord[2] = "lipton"; //overwriting ord[2]
ord[3] = "mus"; //overwriting ord[3]
ord[4] = "orkester"; //overwriting ord[4]
ord[5] = "toving"; //overwriting ord[5]
答案 2 :(得分:0)
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
您从未填充ordet
数组,只是覆盖了ord
数组。
此时,ordet
数组中没有元素,只有null
s。
因此...
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
是与不存在的元素进行比较,#compareTo
抛出NullPointerException,因为您传入的是null
,而不是String