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

+1 vote

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);

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());
}
}
}```