I am learning java and doing some practice problems. My code works, but I feel like I used a workaround sort of way to accomplish it. Is there another way to express what I want the program to do?
Question: Problem J4: Time on task
Input specification:
First line is the total number of minutes to accomplish the chores.
Second line is number of chores to choose from
The next 'n' lines are how long each chore takes to complete.
Output specification:
The total amount of chores one can do given the amount of time
My code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Time {
public static void main(String args[]) {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
//get the amount of time
int maxMins = Integer.parseInt(input.readLine());
//get the total amount of chores
int totalChores = Integer.parseInt(input.readLine());
//create an array to store each chore and how long it takes to complete it
int[] list = new int[totalChores];
for (int i = 0; i < totalChores; i++) {
list[i] = Integer.parseInt(input.readLine());
}
Arrays.sort(list);
//initialize counters, one for minutes and the other for chores done
int totalMins = 0;
int chores = 0;
//I don't like the below part, not quite sure how to change it
for (int j = 0; totalMins < maxMins; j++) {
totalMins = totalMins + list[j];
if (totalMins <= maxMins) {
chores++;
}
}
System.out.println(chores);
} catch (IOException e) {
e.printStackTrace();
}
}
}