I'm learning Java and I created a simple solution for the following problem:
Given a file
[filename].txt
such that each line has the formatstring, double
, find the minimum possible difference between any two values and identify if it is less than an arbitrary valuemindDist
I am looking on advice on if there are any other possible errors / exceptions I may have missed, in addition to any way of increasing the efficiency / simplicity of my code. Thank you.
This is my solution:
package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) { try {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
Scanner inFile = new Scanner(new File(sc.nextLine()));
sc.close();
List<Double> l = new ArrayList<>();
while (inFile.hasNextLine()) {
String[] parts = inFile.nextLine().split(",");
l.add(Double.parseDouble(parts[1]));
}
Collections.sort(l);
double minDist = 5;
double diff;
double minDiff = Double.MAX_VALUE;
for (int i = 1; i < l.size(); i++) {
diff = l.get(i) - l.get(i - 1);
if (diff < minDiff) minDiff = diff;
}
if (minDiff < minDist) System.out.println("The satellites are not in safe orbits.");
else System.out.println("The satellites are in safe orbits.");
if (l.size()!=1) System.out.println("The minimum distance between orbits (km): " + minDiff);
inFile.close();
} catch (NumberFormatException | FileNotFoundException | ArrayIndexOutOfBoundsException e) {
System.err.println(e);
}
}
}