Reputation: 5
for some reason I can't get Strings compareTo method to work. I get this error message:
exception in thread main java.lang.NullpointerException
at java.lang.String.compareTo(Unknown Source)
at Sort.main(Sort.java:27)
What can I do to fix this? (this code demands that the to arrays are allready sorted individually.)
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];
}
}
}
Upvotes: 0
Views: 830
Reputation: 1168
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
You never filled the ordet
array, you just over-wrote the ord
array.
At this point there is no elements in the ordet
array, just null
s.
So...
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
is comparing to an element that doesnt exist, and #compareTo
throws a NullPointerException because you passed in a null
, not a String
Upvotes: 0
Reputation: 46
You never assign any values to ordet. so compareTo is comparing a string to 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]
Upvotes: 0
Reputation: 3381
Do you mean - it looks like you are setting the wrong array:
String[] ordet = new String[6];
ordet[0] = "akilles";
ordet[1] = "kopper";
ordet[2] = "lipton";
ordet[3] = "mus";
ordet[4] = "orkester";
ordet[5] = "toving";
Upvotes: 5