import java.io.IOException;
import java.net.URI;
import java.util.*;
class Handler implements URLHandler {
String str = "";
public String handleRequest(URI url) {
if (url.getPath().contains("/add-message")) {
String[] parameters = url.getQuery().split("=");
if (parameters[0].equals("s")) {
str = str + parameters[1] + "\n";
}
} else {
return str + "\nuse /add-message?s= to add to the string";
}
return str;
}
}
class StringServer {
public static void main(String[] args) throws IOException {
if(args.length == 0){
System.out.println("Missing port number! Try any number between 1024 to 49151");
return;
}
int port = Integer.parseInt(args[0]);
Server.start(port, new Handler());
}
}
All of the following URL requests go through the handleRequest(URI url) method
Adding "hello"
- This runs through the handleRequest() method and the first if statement since it has "/add-message"
- Then it goes through the next if statement since the first parameter is "s"
- Then the str field is "hello \n"
Adding "world"
- Runs through the same path as previous URL request.
- Now, str field is "hello \n world \n"
We would initially remove the smallest element (1.0), and the average should be (1.0 + 2.0 + 3.0)/3 = 2.0. However, the method returns 3.6666. This is because the method removes all doubles equal to the smallest element, so it removes both 1.0s, leading to the erroneous calculation.
double[] input1 = {1.0, 1.0, 2.0, 3.0};
assertEquals(2.0, ArrayExamples.averageWithoutLowest(input), 0.0);
This method does not induce a failure because there is only one instance of the smallest element, 1.0. Therefore, it will function correctly and get the correct 2.5 average.
double[] input2 = {1.0, 2.0, 3.0};
assertEquals(2.5, ArrayExamples.averageWithoutLowest(input2), 0.0);
The original buggy code was:
static double averageWithoutLowest(double[] arr) {
if(arr.length < 2) { return 0.0; }
double lowest = arr[0];
for(double num: arr) {
if(num < lowest) { lowest = num; }
}
double sum = 0;
for(double num: arr) {
if(num != lowest) { sum += num; }
}
return sum / (arr.length - 1);
}
I fixed it to be:
static double averageWithoutLowest(double[] arr) {
if(arr.length < 2) { return 0.0; }
double lowest = arr[0];
for(double num: arr) {
if(num < lowest) { lowest = num; }
}
double sum = 0;
for(double num: arr) {
sum += num;
}
sum -= lowest;
return sum / (arr.length - 1);
}
- I deleted the if statement within the for loop and then just subtracted the lowest number.
- The problem with the original code was that when there was that if there were two or more values that coincided with lowest, it would not include both of them.
- My fix includes all the values and subtracts the lowest so it will only remove one value
- Week 2 introduced me to the URIHandler interface in Java. I learned how to handle URI/URLs in Java and a simple overview of how they work with queries and other simple features.