- Create a function
getInstance()
in register Class. Return the singleton instance of a register class using the register variable which was declared and initiated to null. - Complete
getTotalBill
function in the editor below. The function must state what must be returned.The function has following parameteritemDetails
: a key/value pair of string key and integer value
The register contains the list of items and their prices. In this exercise, the list of items and their prices are:
Item - Price
apple - 2.0
orange - 1.5
mango - 1.2
grapes - 1.0
Input : It contains the string which have the list of purchased items (fruits) and their quantity .Note : The order of the fruit's details may vary.
Sample input: apple 30 orange 10 mango 20 Output: 99.0
Sample input: orange 10 grape 52 apple 14 Output: 95.0
I have tried but it is not giving proper output any suggestions..
class Register {
private static final Register register = new Register();
/**
* Complete the 'getTotalBill' function below.
* The function is expected to return a STRING.
* The function accepts MAP itemDetails as parameter.
*/
public Register() {
}
public static Register getInstance() {
return register;
}
public Double getTotalBill(Map<String, Integer> itemDetails) {
Map<String, Double> stocks = new HashMap<>();
stocks.put("apple", 2.0);
stocks.put("orange", 1.5);
stocks.put("mango", 1.2);
stocks.put("grape", 1.0);
// Write your code here
double sum = 0;
for (Map.Entry<String, Integer> entry : itemDetails.entrySet()) {
for (Map.Entry<String, Double> entry1 : stocks.entrySet()) {
if (entry.getKey() == entry1.getKey()) {
sum += entry.getValue() * entry1.getValue();
}
}
}
return sum;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
Scanner readInput = new Scanner(System.in);
String[] input = readInput.nextLine().split(" ");
Map<String, Integer> myItems = new HashMap<String, Integer>();
for (int i = 0; i < input.length; i += 2) {
myItems.put(input[i], Integer.parseInt(input[i + 1]));
}
Register regObj = Register.getInstance();
System.out.println(regObj.getTotalBill(myItems));
readInput.close();
}
}