In: Computer Science
1.Note: The following code is written only in main -- you assume there is an array bag and you are not adding any methods to that bag.
Write the main program to create two array bags of type string. Place 5 strings of your choice in the first bag and 5 strings (of your choice) in the second bag. Your program must:
a) determine if there are any strings in the first bag that appears in the second bag as well. If there are, print there are repeated strings. Else print the bags have unique values.
b) Print the content of both bags and if there are repeated values, print that value only once.
Here i solved your problem in JAVA lanuage.
Code:
import java.util.Arrays;
import java.util.HashSet;
public class Main
{
public static void main(String[] args)
{
// enter string value for both bags
String[] bag1 = {"C", "C++", "C#", "JAVA", "SQL"};
String[] bag2 = {"SQL", "PHP", "Android", "ORACLE", "JAVA"};
int staus=0;
// print both the bags.
System.out.println("Bag1 : "+Arrays.toString(bag1));
System.out.println("Bag2 : "+Arrays.toString(bag2));
HashSet<String> set = new HashSet<String>(); //it is used to store common strings from both bags
for (int i = 0; i < bag1.length; i++)
{
for (int j = 0; j < bag2.length; j++)
{
if(bag1[i].equals(bag2[j])) //check 2 string is equal
{
set.add(bag1[i]); //if equal then store into set
staus=1;
}
}
}
if(staus==1)
System.out.println("\nCommon string in both bags: "+(set)); // print common strings.
else
System.out.println("\nNo any commmon string in both bags"); //if no any common string then print message
}
}
Output: