Home > Software engineering >  How to display and add tasks to file according to priorities using Java
How to display and add tasks to file according to priorities using Java

Time:12-25

I need to display/list the contents of a txt file in the ascending order of priority. So, should I need to take a seperate input for priority of task or can I splice the input line?

private static void show() {
    
    String[] items = getData("task.txt");
    
    if (items.length == 0) {
        System.out.println("There are no pending tasks!");
    } else {
        for (int i = items.length - 1; i >=0; i--) {    
                System.out.printf("[%d] %s\n", i   1, items[i]);
            
        }
    }

My getData looks like this:

private static String[] getData(String file) {
    ArrayList<String> dataList = new ArrayList<>();
    Scanner s=null;
    
    try {
         s = new Scanner(new FileReader(file));
        while (s.hasNextLine()){
            dataList.add(s.nextLine());
        }s.close();
    } catch (Exception e) {
        System.out.println("Problem to open \"task.txt\".");
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (Exception e) {
            }
        }
    }

    String[] items = new String[dataList.size()];
    for (int i = 0; i < items.length; i  ) {
        items[i] = dataList.get(i);
    }

    return items;
}

Input:
10 the thing i need to do
5 water the plants
11 clean house

Output:
5 water the plants
10 the thing i need to do
11 clean house

CodePudding user response:

You can just sort the ArrayList datalist: (I am assuming that the "priority item" format is already in it)

dataList.sort((o1, o2) -> {
        Integer priority1 = Integer.parseInt(o1.split(" ")[0]);
        Integer priority2 = Integer.parseInt(o2.split(" ")[0]);
        return priority1.compareTo(priority2);
    });

Put this right after the try-catch-finally-block.

  • Related