In: Computer Science
The following Assignment Questions are related to Java Collection Interfaces (Queue, List, Map, Set, etc), and Java IOStream.
Write a function that counts the occurrence of a specific letter (Eg. “a”) in a file. Where the letter can be defined at the prompt line (command line). [3 Marks].
1)
Collection and Map both are interfaces in java. util package but Collection is used to store objects and Map is used to store the objects for (key,value) based manner. Collection classes are used to store object in array format. and Map classes are used to store in (KEY,VALUE) pair format
2)
By defining a Interface/class generic you are making it type-safe i.e. it can act up on any datatype
We need because 1)Type check at compile time
2)code reuse
3)
Set is acollection that cann't contains dublicate elements
1)HashSet
2)LinkedHashSet
3)TreeSet
// Java program to demonstrate a Set
import java.util.*;
public class SetExample{
public static void main(String[] args)
{
// Set demonstration using
HashSet
Set<String> hash_Set
= new
HashSet<String>();
hash_Set.add("code");
hash_Set.add("For");
hash_Set.add("code");
hash_Set.add("Example");
hash_Set.add("Set");
System.out.println(hash_Set);
}
}
output:-
[Set, Example, code, For]
4)
List<String> trimmedStrings = new
ArrayList<String>();
for(String s : originalStrings) { //Advanced for loop
trimmedStrings.add(s.trim());
}
originalStrings = trimmedStrings;
or
List<String> myList = Arrays.asList(" A", "B ", " C
");
return myList.stream().(str -> str.trim());
5)
class Myclass{
public static void main(String args[]){
int arr[]={1,2,3,4,5,6,7,8};
func(arr,arr.length);
}
public static func(int arr,int l){
for(int i=0;i<li++){
System.out.print(arr[i]);
}
}
}
6)
// C program to illustrate
// command line arguments
#include<stdio.h>
int main(int argc,char* argv[])
{
char counter;
int result;
printf("Program Name Is: %s",argv[0]);
if(argc==1)
printf("\nNo Extra Command Line
Argument Passed Other Than Program Name");
if(argc>=2)
{
counter=argv[1]
result=func(counter);
printf("%d",result);
return 0;
}
int func(char s){
int count=0;
char ch, file_name[25];
FILE *fp;
printf("Enter name of a file you wish to compare the element
\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF)
if(ch==s){
count++;
}
fclose(fp);
}
return count;
}
}