ASSIGNMENT NO.
1:
SET A
a) Write a java program to accept names of 'n' cities, insert same into
array list collection and display the contents of same array list, also
remove all these elements.
Program:-
import java.util.ArrayList;
import java.util.Scanner;
public class CityList {
public static void main(String[] args) {
// Create a Scanner object to take input
Scanner scanner = new Scanner(System.in);
// Ask for the number of cities
System.out.print("Enter the number of cities: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character left by nextInt()
// Create an ArrayList to store city names
ArrayList<String> cities = new ArrayList<>();
// Input the names of the cities
System.out.println("Enter the names of " + n + " cities:");
for (int i = 0; i < n; i++) {
String city = scanner.nextLine();
cities.add(city);
}
// Display the contents of the ArrayList
System.out.println("\nCities in the list:");
for (String city : cities) {
System.out.println(city);
}
// Remove all elements from the ArrayList
cities.clear();
// Display the ArrayList after removal
System.out.println("\nAfter removing all elements, the list is now empty: " +
cities);
// Close the scanner
scanner.close();
}
}
Output:-
b) Write a java program to read 'n' names of your friends, store it into
linked list, also display contents of the same.
Program:-
import java.util.LinkedList;
import java.util.Scanner;
public class FriendsList {
public static void main(String[] args) {
// Create a Scanner object to take input
Scanner scanner = new Scanner(System.in);
// Ask for the number of friends
System.out.print("Enter the number of friends: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character left by nextInt()
// Create a LinkedList to store the names of friends
LinkedList<String> friends = new LinkedList<>();
// Input the names of friends
System.out.println("Enter the names of " + n + " friends:");
for (int i = 0; i < n; i++) {
String friend = scanner.nextLine();
friends.add(friend);
}
// Display the contents of the LinkedList
System.out.println("\nFriends in the list:");
for (String friend : friends) {
System.out.println(friend);
}
// Close the scanner
scanner.close();
}
}
Output:-
c) Write a program to create a new tree set, add some colors (string) and
print out the tree set.
Program:-
import java.util.TreeSet;
public class ColorTreeSet {
public static void main(String[] args) {
// Create a TreeSet to store color names
TreeSet<String> colors = new TreeSet<>();
// Add some color names to the TreeSet
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Yellow");
colors.add("Purple");
colors.add("Orange");
// Display the contents of the TreeSet
System.out.println("Colors in the TreeSet:");
for (String color : colors) {
System.out.println(color);
}
}
}
Output:-
d) Create the hash table that will maintain the mobile number and
student name. Display the contact list.
Program:-
import java.util.Hashtable;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
// Create a Hashtable to store mobile numbers and student names
Hashtable<String, String> contactList = new Hashtable<>();
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Asking the user how many contacts they want to add
System.out.print("Enter the number of contacts you want to add: ");
int numContacts = scanner.nextInt();
scanner.nextLine(); // Consume the leftover newline
// Collect contact information from the user
for (int i = 0; i < numContacts; i++) {
System.out.print("Enter mobile number for contact " + (i + 1) + ": ");
String mobileNumber = scanner.nextLine();
System.out.print("Enter student name for contact " + (i + 1) + ": ");
String studentName = scanner.nextLine();
// Add the contact information to the Hashtable
contactList.put(mobileNumber, studentName);
}
// Display the contact list (mobile number and student name)
System.out.println("\nContact List:");
for (var entry : contactList.entrySet()) {
String mobileNumber = entry.getKey();
String studentName = entry.getValue();
System.out.println("Mobile Number: " + mobileNumber + " | Student Name: " +
studentName);
}
// Close the scanner
scanner.close();
}
}
Output:-
Set B
a) Accept 'n' integers from the user. Store and display integers in sorted
order having proper collection class. The collection should not accept
duplicate elements.
Program:-
import java.util.Scanner;
import java.util.TreeSet;
public class SortedIntegers {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);
// Ask for the number of integers to be entered
System.out.print("Enter the number of integers: ");
int n = scanner.nextInt();
// Create a TreeSet to store integers (it will automatically sort and remove
duplicates)
TreeSet<Integer> numbers = new TreeSet<>();
// Accept 'n' integers from the user
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
numbers.add(number); // Add to the TreeSet (duplicates will be ignored)
}
// Display the integers in sorted order (TreeSet does this automatically)
System.out.println("\nSorted integers (without duplicates):");
for (int num : numbers) {
System.out.println(num);
}
// Close the scanner
scanner.close();
}
}
Output:-
b) Write a program to sort HashMap by keys and display the details
before sorting and after sorting.
Program:-
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class SortHashMapByKeys {
public static void main(String[] args) {
// Create a HashMap to store student IDs and their names
HashMap<Integer, String> studentGrades = new HashMap<>();
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user how many student entries they want to add
System.out.print("Enter the number of students: ");
int numStudents = scanner.nextInt();
scanner.nextLine(); // Consume the newline character left by nextInt
// Collect student data from the user
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter student ID (integer): ");
int studentID = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter student name: ");
String studentName = scanner.nextLine();
// Add the student ID and name to the HashMap
studentGrades.put(studentID, studentName);
}
// Display the HashMap before sorting
System.out.println("\nHashMap before sorting by keys:");
for (Map.Entry<Integer, String> entry : studentGrades.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// Sort the HashMap by keys (student IDs) using TreeMap
TreeMap<Integer, String> sortedStudentGrades = new
TreeMap<>(studentGrades);
// Display the HashMap after sorting by keys
System.out.println("\nHashMap after sorting by keys:");
for (Map.Entry<Integer, String> entry : sortedStudentGrades.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// Close the scanner
scanner.close();
}
}
Output:-
c) Write a program that loads names and phone numbers from a text file
where the data is organized as one line per record and each field in a
record are separated by a tab (\t). it takes a name or phone number as
input and prints the corresponding other value from the hash table
(hint: use hash tables)
Program:-
import java.io.*;
import java.util.Hashtable;
import java.util.Scanner;
public class PhoneBook {
public static void main(String[] args) {
// Initialize the Hashtable to store name-phone number pairs
Hashtable<String, String> nameToPhone = new Hashtable<>();
Hashtable<String, String> phoneToName = new Hashtable<>();
// File path where the data is stored
String filePath = "contacts.txt"; // Modify with your file path
// Load data from the text file into the hash tables
loadDataFromFile(filePath, nameToPhone, phoneToName);
// Create Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to input a name or a phone number
System.out.print("Enter a name or phone number: ");
String input = scanner.nextLine();
// Check if the input is a name or phone number
if (nameToPhone.containsKey(input)) {
// Input is a name, fetch the corresponding phone number
System.out.println("Phone number: " + nameToPhone.get(input));
} else if (phoneToName.containsKey(input)) {
// Input is a phone number, fetch the corresponding name
System.out.println("Name: " + phoneToName.get(input));
} else {
// Input is not found in the hash tables
System.out.println("No record found for the input: " + input);
}
// Close the scanner
scanner.close();
}
// Method to load data from the file into the hash tables
private static void loadDataFromFile(String filePath, Hashtable<String, String>
nameToPhone, Hashtable<String, String> phoneToName) {
try {
// Create BufferedReader to read the file
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
// Read each line from the file
while ((line = reader.readLine()) != null) {
// Split the line by tab character (\t)
String[] parts = line.split("\t");
// Ensure we have exactly two parts (name and phone number)
if (parts.length == 2) {
String name = parts[0].trim();
String phoneNumber = parts[1].trim();
// Add the name-phone number pair to the hash tables
nameToPhone.put(name, phoneNumber);
phoneToName.put(phoneNumber, name);
}
}
// Close the file reader
reader.close();
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
Output:-