Created by GrabetsB on 24 02 2015 public class FindTemperatureNearN ul

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Created by GrabetsB on 24.02.2015.
*/
public class FindTemperatureNearNull {
// Nothing critical, can't find
public static double closestToZero(double ts[]) throws Exception {
// Very minor: 4 lines(one variable each) are more preferable in production
// Medium: If assigning floating points constants, add .0 in the end. That makes code simpler to read, and will
// prevent from changing to the wrong variable type.
double minTs = -273, maxTs = 5560, min = -273, max = 5560;
// Minor: Avoid one line ifs
// Medium: Don't skip backers even in one statement blocks. True for all code, btw.
if (ts.length == 0) return 0;
// Very minor: Can use foreach here
for (int i = 0; i < ts.length; i++) {
// Major: Use predefined constants for value argument limitations here, instead of "magic numbers". I would
// also suggest to move constants on the class level.
// Minor/Medium: Throw java.lang.IllegalArgumentException instead of general exception when checking arguments.
if (ts[i] < -273 || ts[i] > 5560) throw new Exception();
else {
// Hard to read... Statement logic is simpler in your way, but i would make something like:
//
// if (ts[i] < 0 && ts[i] > min) {
// min = ts[i]
// } else if (ts[i] > 0 && ts[i] < max) {
// max = ts[i];
// }
// Not a real "real note", just a thought.
// Major: Defiantly needs popper formatting
if (ts[i] < 0) {
if (ts[i] > min)
min = ts[i];
} else if (ts[i] < max)
max = ts[i];
}
}
if (max < Math.abs(min))
return max;
else return min;
}
public static void main(String[] args) throws Exception {
double[] temp = new double[]{-6d, -273d, -1.101245457, 10, 2, 5.123, 1.8246, 0.2, -0.3};
System.out.println(closestToZero(temp));
}
}