As I have already mentioned in this article, I have had a small fiasco at the Java Exam of the SoftUni. Anyway, I managed to pass the exam, so actually if I manage to graduate in my certificate Java would be present. 🙂 As far as I prefer to be able to actually solve the tasks, I have decided to take a look of the Java problems, given at the three exams and to try to solve them one by one.
Tonight I tried to solve the first task of the first the exam – Video Length. I had really a good idea how to solve it, but I found out, that the Java syntax is really weird – it did not recognize my compare strings with “==”, so I simply cheated and I looked at the solution. Thus, I have decided to present you the solution line by line and to explain what it does.
So, here is the first part of the code:
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Scanner; public class Video { public static void main(String[] args) { int totalMinutes = 0; Scanner input = new Scanner(System.in); while (true) { String videoDuration = input.nextLine(); if (videoDuration.equals("End")) { break; } |
So we do the following:
- We initialize int called totalMinutes;
- We initialize object named “input”, that we use to read from the console;
- We start a loop with while(true), and we read each line;
- If the line equals “End” (this is what I was not able to do for quite some time), then we break the while-loop;
The second part:
1 2 3 4 5 6 7 8 9 10 |
String[] tokens = videoDuration.split(":"); int hours = Integer.parseInt(tokens[0]); int minutes = Integer.parseInt(tokens[1]); totalMinutes = totalMinutes + hours * 60 + minutes; } int totalHours = totalMinutes / 60; totalMinutes = totalMinutes % 60; System.out.printf("%d:%02d\n", totalHours, totalMinutes); } } |
So, in the second part:
- We split the string “videoDuration” by the sign “:”. Thus, we receive tokens[0] and tokens[1];
- We parse the tokens[0] into int hours and tokens [1] into minutes;
- Then we calculate the minutes in total, multiplying hours by 60;
- At the end we calculate the total hours and the total minutes (for the minutes we use the % operator, which gives us the remainder only);
- At the end we print the result with System.out.printf. The “02” is needed, in order to obtain 100 points, otherwise it gives you about 70. The “\n” can be skipped.
If you skip the “02” in the last line and you may receive error in the following input:
1 2 3 4 |
0:02 0:59 End 1:1 |