settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: A miner task - Java Task (Maps)

+14 votes

You are given a sequence of strings, each on a new line. Every odd line on the console is representing a resource (e.g. Gold, Silver, Copper, and so on) , and every even – quantity. Your task is to collect the resources and print them each on a new line.

Print the resources and their quantities in format:

{resource} –> {quantity}

The quantities inputs will be in the range [1 … 2 000 000 000]

Examples:

Input

Output

Gold

155

Silver

10

Copper

17

Gold

4

stop

Gold -> 159

Silver -> 10

Copper -> 17

 

asked in Java category by user john7

1 Answer

+1 vote
 
Best answer

Very helpful for understanding this task was THIS POST: https://stackoverflow.com/questions/4820716/finding-repeated-words-on-a-string-and-counting-the-repetitions

Here's my solution (the key here is to understand row 20):

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Pr_06_AMinerTask {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

        String resource = "";
        Integer number;

        while (!(resource = sc.nextLine()).equals("stop")) {//GETTING THE resource RIGHT FROM HERE
            number = Integer.parseInt(sc.nextLine());//GETTING THE NUMBER OF THE resource

            if (!map.containsKey(resource)) {//IF THERE ISN'T (!) A resource IN THE map...
                map.put(resource, number);//...ADD THE resource WITH IT'S CURRENT number
            } else {//IF THERE IS ALREADY THE SAME resource IN THE map...
                map.put(resource, (map.get(resource) + number));//...ADD THE resource, GET IT'S CURRENT NUMBER + ADD IT TO THE NEW ONE
            }
        }

        for (Map.Entry<String, Integer> mapValues : map.entrySet()) {//PRINTING THE OUTPUT
            System.out.printf("%s -> %s\n", mapValues.getKey(), mapValues.getValue());
        }
    }
}
answered by user Jolie Ann
edited by user golearnweb
...