Issue
I am trying to write a program that can identify which delivery driver has the lowest current delivery load.
The drivers name, location and current delivery load are in this format:
Wesley Smith, London, 4
Mark Hammond, London, 2
Abul Ali, London, 12
Ned Cayhill, London, 6
I am trying to write a program that can identify that Mark Hammond (in this instance) has the lowest load and then that entire string will be assigned to a new variable.
I have tried taking the last character (the current delivery load) from all the strings and comparing them all but then I lose a way of reconnecting that number back to its original driver.
Here is the code I have written so far (edited)
ArrayList<String> matchedDrivers = new ArrayList<String>();
ArrayList<Integer> deliveries = new ArrayList<String>();
matchedDrivers.add("Wesley Smith, London, 4");
matchedDrivers.add("Mark Hammond, London, 2");
matchedDrivers.add("Abul Ali, London, 12");
matchedDrivers.add("Ned Cayhill, London, 6");
for(int i = 0;i<matchedDrivers.size();i++)
{
String mDriver = matchedDrivers.get(i);
String load = mDriver.substring(mDriver.lastIndexOf(",") + 1);
int intLoad = Integer.parseInt(load)
deliveries.add(intLoad);
}
Integer max = Collections.max(deliveries);
System.out.println(max);
Thanks in advance!
Solution
You can iterate through the entire list and keep a variable which keeps track of the minimum that have been encountered and a variable name that keeps track of the person who has the minimum value .
To extract the minimum from the list, you can use split function of String class and then get the integer value using Integer.parseInt
class Main {
public static void main(String args[]) {
List<String> r = new ArrayList<>();
r.add("Wesley Smith, London, 4");
r.add("Mark Hammond, London, 2");
r.add("Abul Ali, London,12");
String driver = findLowestLoad(r);
System.out.println(driver);
}
private static String findLowestLoad(List<String> r) {
int min = Integer.MAX_VALUE;
String name = "";
for (int i = 0; i < r.size(); i++) {
int delValue = Integer.parseInt(r.get(i).split(",")[2].trim());
if (delValue < min) {
min = delValue;
name = r.get(i).split(",")[0];
}
}
return name;
}
}
and the output is
Mark Hammond
Answered By - Gurkirat Singh Guliani
Answer Checked By - Marie Seifert (JavaFixing Admin)