public class ReverseList extends HttpServlet {
public static void sort(int arr[]) {
int N = arr.length;
int i, j, temp;
for (i = 1; i< N; i++) {
j = i;
temp = arr[i];
while (j > 0 && temp < arr[j-1]) {
arr[j] = arr[j-1];
j = j-1;
}
arr[j] = temp;
}
}
private void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String jsonStr = "";
if(br != null){
jsonStr = br.readLine();
}
StringReader strReader = new StringReader(jsonStr);
JsonReader reader = Json.createReader(strReader);
JsonObject obj = reader.readObject();
JsonArray inArray = obj.getJsonArray("inList");
int data [];
for (int i = 0; i > inArray.size(); i++) {
data = new int[inArray.getInt(i)];
}
long startTime = System.currentTimeMillis();
this.sort(data);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
JsonArrayBuilder outArrayBuilder = Json.createArrayBuilder();
for(int i = 0; i<data.length; i++) {
outArrayBuilder.add(data[i]);
}
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println("{ \"outList\" : " + outArrayBuilder.build().toString()+"\n");
out.println("algorithim: Insertion Sort\n Execution time:"+ elapsedTime+"}");
}
}
I am trying to convert the JSON Array into an int[], sort the int[], then output it as JSON with the time it took the sort to execute. The error I'm receiving is a NullPointerException.
java.lang.NullPointerException
csi403.ReverseList.sort(ReverseList.java:23)
csi403.ReverseList.doService(ReverseList.java:99)
csi403.ReverseList.doPost(ReverseList.java:44)
This is my first time using a servlet and I don't have an efficient way to make corrections and compile for errors. I am using a combination of Amazon Web Services- Elastic Beanstalk, Postman, and maven to create an HTTP endpoint. So, the question is twofold. Why am I running into this error? And, is there an easier way to compile this code and make corrections. I have heard about a tool called cURL but am unsure how it would be any different from what I am doing now. Any help is appreciated!
The way you create and populate your array before sorting may be near of:
int[] data = new int[inArray.size()];
for( int i = 0; i < inArray.size(); i++) {
data[i] = inArray.getInt( i );
}
To sort an array, you may use java.util.Arrays.sort .
Arrays.sort( data, Collections.reverseOrder());
For the NPE: the condition i > inArray.size()
is always false, so the array remains null, and in sort()
arr.length;
throw the NPE.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.