1.Write code that opens a file called numbers.txt for writing. Use a loop to wri
ID: 3816698 • Letter: 1
Question
1.Write code that opens a file called numbers.txt for writing. Use a loop to write the numbers from 1 through 30 to the file, and close the file.
Write code that opens the numbers.txt (created above).
(i) Read the numbers from the file
(ii) Adds every third number starting from 1
(iii) Display every third number starting from 1 and displays their total.
2. Given the following sets below:
s1 = {1,2,3,4,5} s2 = {2,4,6,8}
s3 = {1,5,9,13,17}
Write code for the following questions.
(i) Is s1 a subset of s2?
(ii) Is the intersection of s1 and s3 empty? (iii) Union of s1 and s2
(iv) Intersection of s2 and s3
(v) Intersection of s1, s2, and s3
(vi) Difference between s1 and s2 (s1 – s2)
Explanation / Answer
SetOperations.java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class SetOperations {
public static void main(String[] args) {
ArrayList<Integer> s1=new ArrayList<Integer>();
s1.add(1);
s1.add(2);
s1.add(3);
s1.add(4);
s1.add(5);
ArrayList<Integer> s2=new ArrayList<Integer>();
s2.add(2);
s2.add(4);
s2.add(6);
s2.add(7);
ArrayList<Integer> s3=new ArrayList<Integer>();
s3.add(1);
s3.add(5);
s3.add(9);
s3.add(13);
s3.add(17);
Set set1=new HashSet<Integer>(s1);
Set set2=new HashSet<Integer>(s2);
Set set3=new HashSet<Integer>(s3);
Set set4=new HashSet<Integer>(s1);
Set set5=new HashSet<Integer>(s2);
boolean bool=s1.containsAll(s2);
if(bool)
System.out.println("s1 is subset of s2");
else
System.out.println("s1 is not subset of s2");
set1.retainAll(set2);
if(set1.size()>0)
System.out.println("There are common elements between s1 and s2");
else
System.out.println("There are no common elements between s1 and s2");
set2.retainAll(set3);
System.out.print("The Intersection of s2 and s3 is :");
System.out.println(set2);
System.out.print("The Intersection of s1,s2 and s3 is :");
s2.retainAll(s3);
s1.retainAll(s2);
System.out.println(set1);
System.out.print(" Difference between s1 and s2 (s1 – s2):");
set4.removeAll(set5);
System.out.println(set4);
}
}
___________________
output:
s1 is not subset of s2
There are common elements between s1 and s2
The Intersection of s2 and s3 is :[]
The Intersection of s1,s2 and s3 is :[2, 4]
Difference between s1 and s2 (s1 – s2):[1, 3, 5]
_________________
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.