After a week or so, I have started to master Java, as a part of the courses at the SoftUni. Today, I tried to resolve one of the problems, given about 3 weeks ago at the exam – CountBeers.
The problem is a bit trivial and very similar to the video length problem, discussed here. Long story short, you have the following input from the console:
41 beers
1 stacks
19 beers
End
Then you simply should calculate the number of beers, multiplying by 20, for each stack. I used some of the code from the previous problem, and I managed to come up with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.*; public class CountBeers { public static void main(String[] args) { int totalBeers = 0; Scanner input = new Scanner(System.in); while (true) { String beerInput = input.nextLine(); if (beerInput.equals("End")) { break; } String[] beers = beerInput.split(" "); int beerCount = Integer.parseInt(beers[0]); String beerUnit = beers[1]; if (beerUnit.equals("stacks")) { totalBeers += (20 * beerCount); } else { totalBeers += beerCount; } } int totalStacks = totalBeers / 20; int totalBeerBottles = totalBeers % 20; System.out .printf("%d stacks + %d beers", totalStacks, totalBeerBottles); } } |
It is really easy, once you manage to use the “while(true)” loop correctly and to split the beers string into integer and string. The third part of the solution is the usage of the operator “%”, which is quite OK. The hard-coding of the example is not really a best practise, but I think it is OK for the goal.
Last but not least, you may take a look at the original solution of the problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Scanner; public class CountBeers { public static void main(String[] args) { Scanner input = new Scanner(System.in); int totalBeers = 0; while (true) { String orderLine = input.nextLine(); if (orderLine.equals("End")) { break; } String[] order = orderLine.split(" "); int beers = Integer.parseInt(order[0]); if (order[1].equals("stacks")) { beers *= 20; } totalBeers += beers; } System.out.printf("%d stacks + %d beers\n", totalBeers / 20, totalBeers % 20); } } |
🙂