Question: Variable groceryArchive is declared as a HashSet. Then, integer numGroceries is read from input representing the number of strings to be read next. For each

Variable groceryArchive is declared as a HashSet. Then, integer numGroceries is read from input representing the number of strings to be read next. For each string read into variable grocery:
Add grocery to groceryArchive.
If grocery is successfully added, output "Grocery entered: ", followed by grocery.
Otherwise, output "Duplicate found: ", followed by grocery, and assign duplicateEncountered with true.
End each output with a newline.
Ex: If the input is:
4
mushrooms mushrooms oranges bananas
then the output is:
Grocery entered: mushrooms
Duplicate found: mushrooms
import java.util.HashSet;
import java.util.Scanner;
public class Groceries {
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
HashSet groceryArchive = new HashSet();
int numGroceries;
String grocery;
boolean duplicateEncountered;
numGroceries = scnr.nextInt();
duplicateEncountered = false;
while (numGroceries >0){
if (!duplicateEncountered){
grocery = scnr.next();
/* Your code goes here */
}
--numGroceries;
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!