├── data.txt ├── binarysort.java ├── README.md ├── RepIdTodayClass.java ├── Question9.java ├── sales.txt ├── Question7.java ├── Question6.java ├── Question4.java ├── .vscode └── launch.json ├── Question5.java ├── Question3.java ├── Question1.java ├── Question10.java ├── Question11.java ├── Question8.java ├── Question2.java └── Question12.java /data.txt: -------------------------------------------------------------------------------- 1 | HI THIS IS A TEST MESSAGE FROM SRC 2 | Check Test Sabeer -------------------------------------------------------------------------------- /binarysort.java: -------------------------------------------------------------------------------- 1 | public class binarysort { 2 | public static void main(String[] args) { 3 | 4 | int[] arr = {10, 20, 30, 40, 50, 60, 70}; 5 | int target = 40; 6 | int start = 0; 7 | int limit = arr.length - 1; 8 | 9 | while (start <= limit) { 10 | int mid = (start + limit) / 2; 11 | if (arr[mid] == target) { 12 | System.out.println("Target "+ target +" is at index: " + mid); 13 | break; 14 | } else if (arr[mid] < target) { 15 | start = mid + 1; 16 | } else { 17 | limit = mid - 1; 18 | } 19 | } 20 | }} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Programming Fundamentals – Course Solutions 2 | 3 | Welcome to the repository containing all Java programs I solved during my **Programming Fundamentals** course. This repo includes solutions to key concepts like conditionals, loops, arrays, file handling, object-oriented programming, and more. 4 | 5 | ## 📚 Course Overview 6 | 7 | The **Programming Fundamentals** course covers the basics of Java and introduces students to problem-solving using structured and object-oriented approaches. These assignments and exercises were designed to help reinforce core programming logic and real-world applications. 8 | 9 | ## 🛠 Technologies Used 10 | 11 | - **Language**: Java (JDK 17+ recommended) 12 | - **IDE**: IntelliJ IDEA / Eclipse / VS Code 13 | - **Build Tool**: None (Simple `.java` files, compiled and run via terminal or IDE) 14 | 15 | ## 🗂 Directory Structure 16 | 17 | 18 | 19 | 20 | **© 2025 Syed Sabeer Faisal** 21 | -------------------------------------------------------------------------------- /RepIdTodayClass.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.BufferedReader; 3 | import java.io.FileReader; 4 | import java.io.IOException; 5 | // this code is same as file reader which i coded 6 | public class RepIdTodayClass { 7 | public static void main(String[] args) { 8 | String targetItemCode = "E011"; // Hardcoded to filter only E011 9 | int totalQuantity = 0; 10 | 11 | try { 12 | BufferedReader reader = new BufferedReader(new FileReader("sales.txt")); 13 | String line; 14 | 15 | reader.readLine(); // Skip header line 16 | 17 | while ((line = reader.readLine()) != null) { 18 | String[] fields = line.split("\t"); 19 | 20 | if (fields.length >= 5) { 21 | String itemCode = fields[2]; // Assuming 3rd column is ItemCode 22 | 23 | // Use equalsIgnoreCase or equals for content comparison 24 | if (itemCode.equalsIgnoreCase(targetItemCode)) { 25 | int quantity = Integer.parseInt(fields[4]); 26 | totalQuantity += quantity; 27 | System.out.println(line); // Show matching line 28 | } 29 | } 30 | } 31 | 32 | reader.close(); 33 | System.out.println("Total quantity purchased for ItemCode E011 is: " + totalQuantity); 34 | 35 | } catch (IOException e) { 36 | System.out.println("Error reading the file."); 37 | } catch (NumberFormatException e) { 38 | System.out.println("Error parsing numbers from the file."); 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Question9.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // To read text from input stream efficiently, line by line 2 | import java.io.FileReader; // To read data from a file 3 | import java.io.IOException; // To handle exceptions when file operations fail 4 | 5 | public class Question9 { 6 | public static void main(String[] args) { 7 | int totalAmount = 0; // Variable to keep track of the total amount for all items 8 | 9 | try { 10 | // Create BufferedReader object to read from "sales.txt" file 11 | BufferedReader reader = new BufferedReader(new FileReader("sales.txt")); 12 | String line; // To hold each line read from the file 13 | 14 | // Read and skip the first line because it is the header (column names) 15 | reader.readLine(); 16 | 17 | // Read each line from the file until there are no more lines (EOF) 18 | while ((line = reader.readLine()) != null) { 19 | // Split the line into fields using tab ("\t") as delimiter 20 | // This creates an array where each element is a field from the line 21 | String[] fields = line.split("\t"); 22 | 23 | // Parse quantity from the 5th field (index 4) as integer 24 | int quantity = Integer.parseInt(fields[4]); 25 | 26 | // Parse unit price from the 6th field (index 5) as integer 27 | int unitPrice = Integer.parseInt(fields[5]); 28 | 29 | // Calculate total price for this line: quantity * unit price 30 | // Add this amount to the running totalAmount variable 31 | totalAmount += quantity * unitPrice; 32 | } 33 | 34 | // Close the file reader after processing all lines to free resources 35 | reader.close(); 36 | 37 | // Print the total amount to pay for all items combined 38 | System.out.println("Total amount of all items purchased: " + totalAmount); 39 | 40 | } catch (IOException e) { 41 | // This block runs if there is an error while reading the file (e.g., file not found) 42 | System.out.println("Error reading the file."); 43 | } catch (NumberFormatException e) { 44 | // This block runs if there is an error parsing quantity or price as integers 45 | System.out.println("Error parsing numbers from the file."); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /sales.txt: -------------------------------------------------------------------------------- 1 | Date Region Rep ID Product Qty Unit Price 2 | 17-June-2019 North E011 Product D 22 5 3 | 23-June-2019 North E011 Product D 24 5 4 | 26-June-2019 North E011 Product C 9 8 5 | 29-June-2019 North E011 Product C 6 8 6 | 2-July-2019 North E011 Product D 7 5 7 | 4-July-2019 North E011 Product D 15 5 8 | 8-July-2019 North E011 Product B 19 15 9 | 20-July-2019 North E011 Product A 23 10 10 | 22-July-2019 North E011 Product A 10 10 11 | 23-July-2019 North E011 Product A 13 10 12 | 1-Aug-2019 North E011 Product B 22 15 13 | 7-Aug-2019 North E011 Product B 12 15 14 | 9-Aug-2019 North E011 Product C 10 8 15 | 15-Aug-2019 North E011 Product B 18 15 16 | 21-Aug-2019 North E011 Product C 13 8 17 | 22-Aug-2019 North E011 Product A 20 10 18 | 27-Aug-2019 North E011 Product B 17 15 19 | 1-June-2019 South E012 Product A 23 10 20 | 5-June-2019 South E012 Product B 19 15 21 | 8-June-2019 South E012 Product C 23 8 22 | 16-June-2019 South E012 Product B 24 15 23 | 19-June-2019 South E012 Product C 17 8 24 | 25-June-2019 South E012 Product A 17 10 25 | 28-June-2019 South E012 Product B 7 15 26 | 13-July-2019 South E012 Product B 13 15 27 | 26-July-2019 South E012 Product C 7 8 28 | 28-July-2019 South E012 Product A 21 10 29 | 12-Aug-2019 South E012 Product A 14 10 30 | 19-Aug-2019 South E012 Product D 12 5 31 | 28-Aug-2019 South E012 Product A 7 10 32 | 2-June-2019 East E013 Product C 20 8 33 | 4-June-2019 East E013 Product B 8 15 34 | 10-June-2019 East E013 Product C 20 8 35 | 11-June-2019 East E013 Product D 18 5 36 | 20-June-2019 East E013 Product B 23 15 37 | 1-July-2019 East E013 Product C 15 8 38 | 5-July-2019 East E013 Product D 22 5 39 | 7-July-2019 East E013 Product C 21 8 40 | 16-July-2019 East E013 Product B 7 15 41 | 17-July-2019 East E013 Product B 19 15 42 | 31-July-2019 East E013 Product B 24 15 43 | 10-Aug-2019 East E013 Product B 15 15 44 | 13-Aug-2019 East E013 Product C 15 8 45 | 16-Aug-2019 East E013 Product C 8 8 46 | 24-Aug-2019 East E013 Product A 11 10 47 | 7-June-2019 West E014 Product B 23 15 48 | 13-June-2019 West E014 Product C 24 8 49 | 14-June-2019 West E014 Product A 22 10 50 | 22-June-2019 West E014 Product B 18 15 51 | 10-July-2019 West E014 Product A 19 10 52 | 11-July-2019 West E014 Product D 15 5 53 | 14-July-2019 West E014 Product D 8 5 54 | 19-July-2019 West E014 Product D 6 5 55 | 25-July-2019 West E014 Product A 9 10 56 | 29-July-2019 West E014 Product A 18 10 57 | 3-Aug-2019 West E014 Product C 25 8 58 | 4-Aug-2019 West E014 Product D 11 5 59 | 6-Aug-2019 West E014 Product B 10 15 60 | 18-Aug-2019 West E014 Product A 7 10 61 | 25-Aug-2019 West E014 Product D 12 5 62 | -------------------------------------------------------------------------------- /Question7.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // To read text line by line 2 | import java.io.FileReader; // To open the file 3 | import java.io.IOException; // To handle file errors 4 | 5 | public class Question7 { 6 | public static void main(String[] args) { 7 | try { 8 | // Open the file 9 | FileReader fileReader = new FileReader("data.txt"); 10 | BufferedReader reader = new BufferedReader(fileReader); 11 | 12 | // Read one line from the file 13 | String line = reader.readLine(); 14 | 15 | // Check if the line is not empty 16 | if (line != null) { 17 | // Split the line into fields using TAB 18 | String[] fields = line.split("\t"); 19 | 20 | // Loop to print each field 21 | for (int i = 0; i < fields.length; i++) { 22 | System.out.println("Field " + (i + 1) + ": " + fields[i]); 23 | } 24 | } else { 25 | System.out.println("The file is empty."); 26 | } 27 | 28 | // Close the reader 29 | reader.close(); 30 | 31 | } catch (IOException e) { 32 | System.out.println("Error reading the file."); 33 | } 34 | } 35 | } 36 | 37 | 38 | // Explanation 39 | // 1. Import necessary classes: 40 | // - FileReader: Opens the file for reading. 41 | // - BufferedReader: Makes it easier to read full lines of text. 42 | // - IOException: Handles errors that may happen while reading the file. 43 | 44 | // 2. Start the program with a try-catch block to safely handle file reading. 45 | 46 | // 3. In the try block: 47 | // - Create a FileReader for the file "data.txt". 48 | // - Wrap it with BufferedReader so you can read entire lines at once. 49 | 50 | // 4. Read the first line from the file using reader.readLine(). 51 | 52 | // 5. Check if the line is not null (not empty): 53 | // - If the file has some content, continue. 54 | // - If not, print "The file is empty." 55 | 56 | // 6. Split the line wherever there is a TAB (\t): 57 | // - This creates an array called fields, with each item being one field of data. 58 | 59 | // 7. Use a for loop to go through each field: 60 | // - Start from index 0 to the end of the array. 61 | // - Print each field with its position like: "Field 1: ...", "Field 2: ..." and so on. 62 | 63 | // 8. Close the file after reading using reader.close() to avoid memory or file access issues. 64 | 65 | // 9. Catch block: 66 | // - If an error occurs (like the file not found), print an error message. 67 | -------------------------------------------------------------------------------- /Question6.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // Helps read text line by line 2 | import java.io.FileReader; // Opens the file 3 | import java.io.IOException; // Handles input/output errors 4 | 5 | public class Question6 { 6 | public static void main(String[] args) { 7 | try { 8 | // Open the file 9 | FileReader fileReader = new FileReader("data.txt"); 10 | BufferedReader reader = new BufferedReader(fileReader); 11 | 12 | // Read the first line from the file 13 | String line = reader.readLine(); 14 | 15 | // Check if line is not null (file is not empty) 16 | if (line != null) { 17 | // Split the line into fields using TAB character ("\t") 18 | String[] fields = line.split("\t"); 19 | 20 | // Loop through each field and print it 21 | for (int i = 0; i < fields.length; i++) { 22 | System.out.println("Field " + (i + 1) + ": " + fields[i]); 23 | } 24 | } else { 25 | System.out.println("File is empty."); 26 | } 27 | 28 | // Close the file 29 | reader.close(); 30 | 31 | } catch (IOException e) { 32 | System.out.println("Error reading the file."); 33 | } 34 | } 35 | } 36 | 37 | 38 | // Explanation 39 | // 1. Import required classes: 40 | // - FileReader: To open the file. 41 | // - BufferedReader: Makes it easy to read one full line at a time. 42 | // - IOException: Handles any file reading errors (like file not found). 43 | 44 | // 2. Inside the main method, we use a try-catch block to safely handle file operations. 45 | 46 | // 3. Inside the try block: 47 | // - Open the file "data.txt" using FileReader. 48 | // - Wrap it with BufferedReader to read the full line. 49 | // - Use readLine() to read the first line from the file. 50 | 51 | // 4. Check if the line is not null: 52 | // - If the file is not empty, go ahead and process the line. 53 | // - If it’s empty, print "File is empty." 54 | 55 | // 5. Split the line: 56 | // - Use line.split("\t") to break the line into parts wherever a TAB (\t) is found. 57 | // - This gives you an array of fields (pieces of data). 58 | 59 | // 6. Use a loop to go through each field and print it: 60 | // - for (int i = 0; i < fields.length; i++) means we are going over each item in the array. 61 | // - Print each field with its number like: "Field 1: value" 62 | 63 | // 7. Close the file after reading to free up resources using reader.close(). 64 | 65 | // 8. Catch block: 66 | // - If there’s any error (like file not found), show a user-friendly error message. -------------------------------------------------------------------------------- /Question4.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // Helps read text line by line 2 | import java.io.FileReader; // Opens the file 3 | import java.io.IOException; // Handles input/output errors 4 | 5 | public class Question4 { 6 | public static void main(String[] args) { 7 | try { 8 | // Open the file using FileReader 9 | FileReader fileReader = new FileReader("data.txt"); 10 | // FileReader reads one character at a time, which is: 11 | // Harder to work with if you want to read a whole line of text 12 | 13 | // Wrap it with BufferedReader to read full lines easily 14 | BufferedReader reader = new BufferedReader(fileReader); 15 | // Reads text from a file efficiently 16 | // Reads line by line, not character by character 17 | 18 | 19 | String line; // This will store each line from the file 20 | 21 | // Keep reading lines one by one until end of file is reached (null) 22 | while ((line = reader.readLine()) != null) { 23 | // Print the current line 24 | System.out.println(line); 25 | } 26 | 27 | // After all lines are read, print this message 28 | System.out.println("END OF THE FILE HAS REACHED"); 29 | 30 | // Close the reader 31 | reader.close(); 32 | 33 | } catch (IOException e) { 34 | // If there's any error (like file not found), show this 35 | System.out.println("Error reading the file."); 36 | } 37 | } 38 | } 39 | 40 | 41 | // Explanation 42 | // 1. Import the Java classes needed: 43 | // - FileReader: To open the file. 44 | // - BufferedReader: To read text line by line easily. 45 | // - IOException: To handle any errors during file operations. 46 | 47 | // 2. Inside main method, use try-catch to handle possible errors. 48 | 49 | // 3. In try block: 50 | // - Open the file using FileReader. 51 | // - Wrap it with BufferedReader for easy line-by-line reading. 52 | 53 | // 4. Create a String variable "line" to store each line read. 54 | 55 | // 5. Use a while loop: 56 | // - The condition (line = reader.readLine()) != null means: 57 | // Keep reading a new line and assign it to "line". 58 | // If the line is not null (file not ended), continue the loop. 59 | // - Inside the loop, print the current line. 60 | 61 | // 6. When no more lines to read (readLine returns null), exit the loop. 62 | 63 | // 7. Print the message "END OF THE FILE HAS REACHED". 64 | 65 | // 8. Close the BufferedReader to free resources. 66 | 67 | // 9. In catch block, print an error message if reading fails. 68 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "java", 9 | "name": "RepIdTodayClass", 10 | "request": "launch", 11 | "mainClass": "RepIdTodayClass", 12 | "projectName": "Java-PF_b2dbf309" 13 | }, 14 | { 15 | "type": "java", 16 | "name": "Question10", 17 | "request": "launch", 18 | "mainClass": "Question10", 19 | "projectName": "Java-PF_b2dbf309" 20 | }, 21 | { 22 | "type": "java", 23 | "name": "Question4", 24 | "request": "launch", 25 | "mainClass": "Question4", 26 | "projectName": "Java-PF_b2dbf309" 27 | }, 28 | { 29 | "type": "java", 30 | "name": "Question3", 31 | "request": "launch", 32 | "mainClass": "Question3", 33 | "projectName": "Java-PF_b2dbf309" 34 | }, 35 | { 36 | "type": "java", 37 | "name": "Question2", 38 | "request": "launch", 39 | "mainClass": "Question2", 40 | "projectName": "Java-PF_b2dbf309" 41 | }, 42 | { 43 | "type": "java", 44 | "name": "Question1", 45 | "request": "launch", 46 | "mainClass": "Question1", 47 | "projectName": "Java-PF_b2dbf309" 48 | }, 49 | { 50 | "type": "java", 51 | "name": "binarysort", 52 | "request": "launch", 53 | "mainClass": "binarysort", 54 | "projectName": "Java-PF_b2dbf309" 55 | }, 56 | { 57 | "type": "java", 58 | "name": "check", 59 | "request": "launch", 60 | "mainClass": "check", 61 | "projectName": "Java-PF_b2dbf309" 62 | }, 63 | { 64 | "type": "java", 65 | "name": "Test", 66 | "request": "launch", 67 | "mainClass": "Test", 68 | "projectName": "Java-PF_b2dbf309" 69 | }, 70 | { 71 | "type": "java", 72 | "name": "Main", 73 | "request": "launch", 74 | "mainClass": "Main", 75 | "projectName": "Java-PF_b2dbf309" 76 | }, 77 | { 78 | "type": "java", 79 | "name": "Current File", 80 | "request": "launch", 81 | "mainClass": "${file}" 82 | } 83 | ] 84 | } -------------------------------------------------------------------------------- /Question5.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // Helps read text line by line 2 | import java.io.FileReader; // Opens the file 3 | import java.io.IOException; // Handles input/output errors 4 | 5 | public class Question5 { 6 | public static void main(String[] args) { 7 | BufferedReader reader = null; // Start with null, means file not opened yet 8 | 9 | try { 10 | // Try to open the file 11 | FileReader fileReader = new FileReader("data.txt"); 12 | reader = new BufferedReader(fileReader); 13 | 14 | // Just read and print the first line (optional step) 15 | String line = reader.readLine(); 16 | System.out.println("File opened successfully. \nFirst line: " + line); 17 | 18 | } catch (IOException e) { 19 | // If file could not be opened or there was an error 20 | System.out.println("File could not be opened."); 21 | } finally { 22 | // This part runs no matter what (success or error) 23 | 24 | // If reader is not null, then the file was opened — so we can close it 25 | if (reader != null) { 26 | try { 27 | reader.close(); // Close the file 28 | System.out.println("File closed successfully."); 29 | } catch (IOException e) { 30 | System.out.println("Error while closing the file."); 31 | } 32 | } else { 33 | // If reader was never assigned, file was not opened 34 | System.out.println("File was not opened."); 35 | } 36 | } 37 | } 38 | } 39 | 40 | // Explanation 41 | 42 | // 1. Import required classes: 43 | // - FileReader: to open the file. 44 | // - BufferedReader: to read text line by line easily. 45 | // - IOException: to handle input/output errors. 46 | 47 | // 2. Start with BufferedReader variable "reader" set to null, 48 | // meaning the file is not opened yet. 49 | 50 | // 3. Use try-catch-finally to safely open, read, and close the file: 51 | 52 | // Inside try block: 53 | // - Try to open the file using FileReader. 54 | // - Wrap FileReader with BufferedReader for easy reading. 55 | // - Read one line (optional) and print it to show file opened. 56 | 57 | // Inside catch block: 58 | // - If an error happens (like file missing), print "File could not be opened." 59 | 60 | // Inside finally block (this runs no matter what): 61 | // - Check if "reader" is not null (file opened successfully). 62 | // If yes, try to close the file and print "File closed successfully." 63 | // - If "reader" is still null (file never opened), print "File was not opened." 64 | // - Also handle any errors during file closing. 65 | 66 | -------------------------------------------------------------------------------- /Question3.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // Helps read text line by line 2 | import java.io.FileReader; // Opens the file 3 | import java.io.IOException; // Handles input/output errors 4 | 5 | public class Question3 { 6 | public static void main(String[] args) { 7 | try { 8 | // Open the file using FileReader 9 | FileReader fileReader = new FileReader("data.txt"); 10 | 11 | // Wrap it with BufferedReader to read full lines easily 12 | BufferedReader reader = new BufferedReader(fileReader); 13 | 14 | // Read ONE LINE from the file 15 | String line = reader.readLine(); // This will read the first line of the file 16 | 17 | // Check if line is not empty or null 18 | // this condion is optional I just added this condition to ensure everything work perfectly including 19 | // error handling 20 | if (line != null) { 21 | // Print the line to the screen 22 | System.out.println("First line from file: " + line); 23 | } else { 24 | System.out.println("File is empty."); 25 | } 26 | 27 | // Close the reader 28 | reader.close(); 29 | 30 | } catch (IOException e) { 31 | // If file is missing or there's an error, print this message 32 | System.out.println("Error reading the file."); 33 | } 34 | } 35 | 36 | 37 | // actually this program is same as Question 1 here we are not using split function to show every word separately 38 | } 39 | 40 | // Explanation 41 | 42 | // 1. Import the built-in Java classes: 43 | // - FileReader: Opens the file from your computer. 44 | // - BufferedReader: Helps read the file line by line (very useful). 45 | // - IOException: Handles any input/output error that might happen. 46 | 47 | // 2. Inside the main method, we use try-catch block: 48 | // - try { } contains the code we *want* to run. 49 | // - catch (IOException e) { } will run *if something goes wrong* (like missing file). 50 | 51 | // 3. In the try block: 52 | // - First, we open the file using: 53 | // FileReader fileReader = new FileReader("data.txt"); 54 | 55 | // 4. Then we wrap it with BufferedReader: 56 | // - BufferedReader reader = new BufferedReader(fileReader); 57 | // - This lets us read full lines easily using `.readLine()`. 58 | 59 | // 5. Now we read ONE line using: 60 | // - String line = reader.readLine(); 61 | // - This will only read the first line of the file (not the whole file). 62 | 63 | // 6. We check if the line is NOT null: 64 | // - That means the file is not empty, so we print it on the screen. 65 | // - If the file is empty (line is null), we show "File is empty." 66 | 67 | // 7. Then we close the file using: 68 | // - reader.close(); → Always close the file after you're done. 69 | 70 | // 8. If anything goes wrong (like file missing or error while reading): 71 | // - The catch block will run and print: "Error reading the file." 72 | 73 | -------------------------------------------------------------------------------- /Question1.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // This lets us read characters from a file 2 | import java.io.FileReader; // This lets us read lines easily 3 | 4 | public class Question1 { 5 | public static void main(String[] args) throws Exception { 6 | 7 | // "throws Exception" means if something goes wrong, 8 | // the program will stop and print the error. 9 | // It's like 'try catch' but simpler for now 10 | 11 | // Create FileReader object to open and read the file "data.txt" 12 | FileReader fileReader = new FileReader("data.txt"); 13 | // Wrap FileReader in BufferedReader to read whole lines easily 14 | BufferedReader reader = new BufferedReader(fileReader); 15 | 16 | // Read one line from the file 17 | String line = reader.readLine(); // Reads a whole line of text 18 | 19 | // Split the line into parts wherever there is a TAB character ("\t") 20 | // This creates an array of words separated by tabs 21 | String[] words = line.split("\t"); 22 | 23 | int i = 0; // Start from the first word (index 0) 24 | 25 | // Loop through the words using while loop 26 | while (i < words.length) { 27 | // Convert the current word to uppercase (capital letters) 28 | String upperWord = words[i].toUpperCase(); 29 | 30 | // Print the uppercase word on the screen 31 | System.out.println(upperWord); 32 | 33 | i++; // Move to the next word 34 | // increment everytime 35 | } 36 | 37 | // Close the file to free resources (always do this after reading a file) 38 | reader.close(); 39 | } 40 | } 41 | 42 | 43 | 44 | // Explanation of This Program 45 | 46 | // 1. First, we import some built-in Java classes: 47 | // - FileReader: This is used to open and read the file. 48 | // - BufferedReader: This helps us read the file line by line easily. 49 | 50 | // 2. Then we create a FileReader object like this: 51 | // FileReader fileReader = new FileReader("data.txt"); 52 | // This line basically tells Java to open the file named "data.txt". 53 | 54 | // 3. Now we wrap that FileReader inside a BufferedReader: 55 | // BufferedReader reader = new BufferedReader(fileReader); 56 | // This makes it easier to read one full line from the file at a time. 57 | 58 | // 4. To read a line from the file, we write: 59 | // String line = reader.readLine(); 60 | // This line reads the first line of text from the file and saves it into a variable called "line". 61 | 62 | // 5. If the file has data separated by TABs (like This Is Sabeer), we can split it like this: 63 | // String[] words = line.split("\t"); 64 | // Now each word (or field) is saved separately in an array called "words". 65 | 66 | // 6. We can use a while loop to go through each word and do something with it: 67 | // For example, printing each word in capital letters using System.out.println(). 68 | 69 | // 7. Finally, we must close the file using: 70 | // reader.close(); 71 | // This is very important. It closes the file and frees up memory so the file doesn’t stay open. 72 | -------------------------------------------------------------------------------- /Question10.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // For reading text from the file efficiently, line by line 2 | import java.io.FileReader; // For reading character files 3 | import java.io.IOException; // For handling input/output exceptions 4 | import java.util.Scanner; // For taking input from the user 5 | 6 | public class Question10 { 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); // Create Scanner object to read user input from console 9 | 10 | // Prompt the user to enter an item code whose total quantity purchased needs to be found 11 | System.out.print("Enter ItemCode to find total quantity purchased: "); 12 | String searchItemCode = scanner.nextLine().trim(); // Read input and remove any leading/trailing spaces 13 | // scanner.nextLine() It reads the entire line of input from the user (or input source) until the end of that line — meaning it captures everything typed until the user presses Enter (newline). 14 | // .trim() remove trailing spaces as also Sir badar explained 15 | 16 | int totalQuantity = 0; // Variable to accumulate total quantity for the entered item code 17 | 18 | try { 19 | // Create BufferedReader to read from the file "sales.txt" 20 | BufferedReader reader = new BufferedReader(new FileReader("sales.txt")); 21 | String line; // Variable to hold each line read from the file 22 | 23 | // Skip the first line since it contains the column headers (not data) 24 | reader.readLine(); 25 | 26 | // Loop through each line of the file until the end is reached (null) 27 | while ((line = reader.readLine()) != null) { 28 | // Split the line into fields using tab as separator 29 | String[] fields = line.split("\t"); 30 | 31 | // Extract the item code from the 3rd column (index 2), called Rep ID here 32 | String itemCode = fields[2]; 33 | 34 | // Compare the extracted item code with the user input (case insensitive) 35 | if (itemCode.equalsIgnoreCase(searchItemCode)) { 36 | // equalsIgnoreCase method: It compares two strings to check if they are equal, ignoring differences in uppercase or lowercase letters. 37 | // If match found, parse the quantity (5th field, index 4) as integer 'qty' 38 | int quantity = Integer.parseInt(fields[4]); 39 | 40 | // Add the quantity to totalQuantity for all itms 41 | totalQuantity += quantity; 42 | } 43 | } 44 | 45 | // Close the file reader after processing to release resources 46 | reader.close(); 47 | 48 | // Print the total quantity of the entered item code purchased by all customers 49 | System.out.println("Total quantity purchased for ItemCode " + searchItemCode + " is: " + totalQuantity); 50 | 51 | } catch (IOException e) { 52 | // Handle errors related to file reading (e.g., file not found) 53 | System.out.println("Error reading the file."); 54 | } catch (NumberFormatException e) { 55 | // Handle errors related to parsing quantity as an integer 56 | System.out.println("Error parsing numbers from the file."); 57 | } finally { 58 | // Close the Scanner to free system resources 59 | scanner.close(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Question11.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | 6 | public class Question11 { 7 | public static void main(String[] args) { 8 | 9 | // Create a HashMap to store sales amounts for each month 10 | // Key = month name (like "June"), Value = total sales amount for that month 11 | HashMap monthSales = new HashMap<>(); 12 | // it stores value in key and value pair for array 13 | 14 | try { 15 | // Open the file "sales.txt" to read data 16 | BufferedReader reader = new BufferedReader(new FileReader("sales.txt")); 17 | String line; 18 | 19 | // Skip the first line because it contains headers, not data 20 | reader.readLine(); 21 | 22 | // Read the file line by line until no more lines 23 | while ((line = reader.readLine()) != null) { 24 | 25 | // Split the current line into parts using tab ("\t") as separator 26 | String[] fields = line.split("\t"); 27 | 28 | // The first part is the date, for example "17-June-2019" 29 | String date = fields[0]; 30 | 31 | // Get the quantity sold from the 5th part (index 4) 32 | int qty = Integer.parseInt(fields[4]); 33 | 34 | // Get the unit price from the 6th part (index 5) 35 | int unitPrice = Integer.parseInt(fields[5]); 36 | 37 | // Calculate total sales for this line = quantity * unit price 38 | int salesAmount = qty * unitPrice; 39 | 40 | // Extract the month part from the date by splitting at "-" 41 | // For "17-June-2019", month is "June" 42 | String month = date.split("-")[1]; 43 | 44 | // Check if the month already has some sales recorded 45 | Integer oldSales = monthSales.get(month); // Get old sales for this month 46 | 47 | if (oldSales == null) { 48 | // If no sales recorded yet for this month, add a new entry 49 | monthSales.put(month, salesAmount); 50 | } else { 51 | // If sales already recorded, add the new sales amount to existing total 52 | monthSales.put(month, oldSales + salesAmount); 53 | } 54 | } 55 | 56 | // Close the file after reading all lines 57 | reader.close(); 58 | 59 | // Now print the total sales for each month 60 | 61 | System.out.println("Month-wise Sales:"); 62 | 63 | // Get all month names as an array 64 | Object[] months = monthSales.keySet().toArray(); 65 | 66 | // Loop through the array using a normal for loop (with index) 67 | for (int i = 0; i < months.length; i++) { 68 | // Convert Object to String because keys are strings 69 | String month = (String) months[i]; 70 | 71 | // Get the sales amount for this month 72 | Integer sales = monthSales.get(month); 73 | 74 | // Print the month and its total sales amount 75 | System.out.println(month + " => " + sales); 76 | } 77 | 78 | } catch (IOException e) { 79 | // If any error happens during file reading, print this message 80 | System.out.println("Error reading the file."); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Question8.java: -------------------------------------------------------------------------------- 1 | // Import for reading text from files efficiently 2 | import java.io.BufferedReader; 3 | import java.io.FileReader; 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | public class Question8 { 11 | public static void main(String[] args) { 12 | // Create a map to store total amount to pay for each ItemCode 13 | Map amountByItemCode = new HashMap<>(); 14 | 15 | try { 16 | // Open the sales.txt file for reading 17 | BufferedReader reader = new BufferedReader(new FileReader("sales.txt")); 18 | String line; 19 | 20 | // Read and skip the first line (header line with column names) 21 | line = reader.readLine(); 22 | 23 | // Read the file line by line until there are no more lines 24 | while ((line = reader.readLine()) != null) { 25 | // Split the current line by tabs to get each field as a string 26 | String[] fields = line.split("\t"); 27 | 28 | // Extract the ItemCode from the 3rd field (index 2) 29 | String itemCode = fields[2]; 30 | // Extract Quantity from the 5th field (index 4) and convert it to an integer 31 | int quantity = Integer.parseInt(fields[4]); 32 | // Extract Unit Price from the 6th field (index 5) and convert it to an integer 33 | int unitPrice = Integer.parseInt(fields[5]); 34 | 35 | // Calculate the amount to pay for this record (quantity * unitPrice) 36 | int amount = quantity * unitPrice; 37 | 38 | // If the itemCode is already in the map, add this amount to the existing total 39 | if (amountByItemCode.containsKey(itemCode)) { 40 | int currentTotal = amountByItemCode.get(itemCode); // get current total 41 | int newTotal = currentTotal + amount; // add new amount 42 | amountByItemCode.put(itemCode, newTotal); // update map with new total 43 | } else { 44 | // If itemCode is not in the map, add it with the current amount 45 | amountByItemCode.put(itemCode, amount); 46 | } 47 | } 48 | 49 | // Close the file after reading all lines 50 | reader.close(); 51 | 52 | // Convert map entries (key-value pairs) into a list for indexed access in a normal for loop 53 | // Here, the Set of entries is passed into the constructor of Array List to create a List of entries 54 | List> entries = new ArrayList<>(amountByItemCode.entrySet()); 55 | // use of amountByItemCode.entrySet() 56 | // amountByItemCode is a Map that stores pairs of ItemCode (String) and total amount (Integer) as i mentioned earlier 57 | // entrySet() is a method of Map that returns a set of entries each entry represents one key-value pair from the map 58 | // example like key sabeer (string) has a value 6198 so when i call sabeer then it will return integer 6198 59 | // So, amountByItemCode.entrySet() returns a Set of Map.Entry objects, where each Map.Entry contains: 60 | // A key (in this case: the ItemCode string) 61 | // A value (in this case: the total amount integer) 62 | 63 | // Use a normal for loop to iterate through the list and print total amount for each ItemCode 64 | for (int i = 0; i < entries.size(); i++) { 65 | Map.Entry entry = entries.get(i); 66 | System.out.println("Total amount to pay for ItemCode " + entry.getKey() + " is: " + entry.getValue()); 67 | // sabeer // 6198 68 | } 69 | 70 | } catch (IOException e) { 71 | // This block runs if there's an error reading the file (e.g., file not found) 72 | System.out.println("Error reading the file."); 73 | } catch (NumberFormatException e) { 74 | // This block runs if there is a problem converting text to a number (e.g., invalid integer) 75 | System.out.println("Error parsing number in the file."); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Question2.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; // This lets us read characters from a file 2 | import java.io.FileNotFoundException; // This lets us read lines easily 3 | import java.io.FileReader; // This helps us catch if file is missing 4 | import java.io.IOException; // This handles input/output errors 5 | 6 | public class Question2 { 7 | public static void main(String[] args) { 8 | 9 | // We will use try-catch to handle errors if the file is not found or can't be read 10 | try { 11 | // Create FileReader object to open and read the file "data.txt" 12 | FileReader fileReader = new FileReader("datsa.txt"); 13 | 14 | // Wrap FileReader in BufferedReader to read whole lines easily 15 | BufferedReader reader = new BufferedReader(fileReader); 16 | 17 | // Read one line from the file 18 | String line = reader.readLine(); // Reads a whole line of text 19 | 20 | // Split the line into parts wherever there is a TAB character ("\t") 21 | // This creates an array of words separated by tabs 22 | String[] words = line.split("\t"); 23 | 24 | int i = 0; // Start from the first word (index 0) 25 | 26 | // Loop through the words using while loop 27 | while (i < words.length) { 28 | // Convert the current word to uppercase (capital letters) 29 | String upperWord = words[i].toUpperCase(); 30 | 31 | // Print the uppercase word on the screen 32 | System.out.println(upperWord); 33 | 34 | i++; // Move to the next word 35 | // increment everytime 36 | } 37 | 38 | // Close the file to free resources (always do this after reading a file) 39 | reader.close(); 40 | } 41 | 42 | //FileNotFoundException is java owns keyword 43 | catch (FileNotFoundException e) { 44 | // This block runs if the file is not found 45 | System.out.println("Error: The file 'data.txt' could not be opened."); 46 | // maybe file is missing or filename is wrong 47 | } 48 | 49 | 50 | catch (IOException e) { 51 | // This block runs if there is a problem while reading the file 52 | System.out.println("Error while reading the file."); 53 | } 54 | } 55 | } 56 | 57 | 58 | 59 | 60 | // Explanation 61 | 62 | // 1. First, we import some built-in Java classes: 63 | // - FileReader: To open the file. 64 | // - BufferedReader: To read the file line by line easily. 65 | // - FileNotFoundException: To handle error when file is missing or name is wrong. 66 | // - IOException: To catch any other errors while reading the file. 67 | 68 | // 2. We use try-catch blocks here. Why? 69 | // Because something might go wrong (like file is missing). 70 | // try { } means "try this code" 71 | // catch (Exception e) { } means "if error happens, do this instead" 72 | 73 | // 3. Inside the try block: 74 | // - We try to open the file using: 75 | // FileReader fileReader = new FileReader("datsa.txt"); 76 | // Note: 'datsa.txt' has a typo, so it will throw an error (which is good for testing). 77 | 78 | // 4. Then we wrap it in BufferedReader like this: 79 | // BufferedReader reader = new BufferedReader(fileReader); 80 | 81 | // 5. After that, we read the first line: 82 | // String line = reader.readLine(); 83 | // And split it using TAB: 84 | // String[] words = line.split("\t"); 85 | 86 | // 6. We go through each word using a while loop and print it in CAPITAL letters. 87 | 88 | // 7. At the end, we close the file using: 89 | // reader.close(); 90 | 91 | // 8. Now the important part — catch blocks: 92 | 93 | // - If the file is NOT FOUND or has a wrong name: 94 | // catch (FileNotFoundException e) { 95 | // System.out.println("Error: The file 'data.txt' could not be opened."); 96 | // } 97 | // So this is how we know the file was NOT opened. 98 | 99 | // - If there’s some other problem while reading (maybe file got corrupted or unreadable): 100 | // catch (IOException e) { 101 | // System.out.println("Error while reading the file."); 102 | // } 103 | 104 | 105 | // inshort We use try-catch block. If the file can't be opened, Java will jump into the catch (FileNotFoundException e) block, and print a message that the file couldn't be opened. That’s how we check if the file was not opened. -------------------------------------------------------------------------------- /Question12.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | import java.util.*; 5 | 6 | public class Question12 { 7 | public static void main(String[] args) { 8 | 9 | // Create a list to store all records (each line of the file) 10 | // Each record is an array of strings (like [date, customer, product, ...]) 11 | List records = new ArrayList<>(); 12 | // List 13 | // You are creating a list (like a resizable array). 14 | 15 | // It will store many String[] (arrays of strings). 16 | 17 | // Each String[] will hold one line from your sales.txt file, split into columns (e.g., date, customer, qty, unit price). 18 | 19 | // example 20 | // String[] line1 = { "17-June-2019", "John", "Phone", "2", "30000" }; 21 | // String[] line2 = { "18-June-2019", "Sara", "Laptop", "1", "90000" }; 22 | 23 | // These arrays are stored inside the list like this: 24 | // records = [line1, line2, ...] 25 | 26 | 27 | 28 | try { 29 | // Open the file named "sales.txt" for reading 30 | BufferedReader reader = new BufferedReader(new FileReader("sales.txt")); 31 | String line; 32 | 33 | // Read the first line (header), e.g. "Date\tCustomer\tProduct\t...\tQty\tUnitPrice" 34 | String header = reader.readLine(); // Save the header to print later 35 | 36 | // Read all remaining lines one by one 37 | while ((line = reader.readLine()) != null) { 38 | 39 | // Split the line into parts using tab (\t) 40 | // Example: "17-June-2019\tJohn\tPhone\t...\t2\t30000" 41 | String[] fields = line.split("\t"); 42 | 43 | // Add this record (line) to the list 44 | records.add(fields); 45 | } 46 | 47 | // Close the file after reading is done 48 | reader.close(); 49 | 50 | // Sort the list in descending order of sales amount 51 | // Sales amount = Quantity (field[4]) * Unit Price (field[5]) 52 | records.sort((a, b) -> { 53 | int qtyA = Integer.parseInt(a[4]); // Quantity from record A 54 | int priceA = Integer.parseInt(a[5]); // Unit Price from record A 55 | int salesA = qtyA * priceA; // Total sales amount of record A 56 | 57 | int qtyB = Integer.parseInt(b[4]); // Quantity from record B 58 | int priceB = Integer.parseInt(b[5]); // Unit Price from record B 59 | int salesB = qtyB * priceB; // Total sales amount of record B 60 | 61 | return Integer.compare(salesB, salesA); // Bigger amount first (descending order) 62 | 63 | // Integer.compare(a, b) Ascending 64 | // Integer.compare(b, a) Descending 65 | 66 | 67 | }); 68 | 69 | // Qty Unit Price Total Sale 70 | // 2 30000 60000 71 | // 5 10000 50000 72 | // 1 100000 100000 73 | 74 | 75 | // Compare 1st and 2nd → 60000 vs 50000 → no swap (60000 is bigger) 76 | 77 | // Compare 2nd and 3rd → 50000 vs 100000 → swap them 78 | 79 | // Then 1st and 2nd again (now 60000 vs 100000) → swap 80 | 81 | // Final order becomes: 82 | 83 | // 1 x 100000 = 100000 84 | 85 | // 2 x 30000 = 60000 86 | 87 | // 5 x 10000 = 50000 88 | 89 | // Print the results 90 | System.out.println(header); // First, print the header again 91 | 92 | // Now print each record in the sorted list 93 | // as we use .length for array similarly we use .size for list 94 | for (int i = 0; i < records.size(); i++) { 95 | // String[] means array of strings 96 | String[] record = records.get(i); // Get each record (array of fields) 97 | System.out.println(String.join("\t", record)); // Join and print 98 | 99 | // String.join("\t", record) takes all the strings inside the record array and combines them into one single string, putting the separator "\t" (a tab character) between each element. 100 | 101 | // Example: 102 | // If I have an array: 103 | // String[] record = { "17-June-2019", "John", "Phone", "2", "30000" }; 104 | // then 105 | // String joined = String.join("\t", record); 106 | // will produce this string: 107 | // "17-June-2019\tJohn\tPhone\t2\t30000" 108 | // final result will be : 17-June-2019 John Phone 2 30000 109 | 110 | 111 | 112 | } 113 | 114 | 115 | } catch (IOException e) { 116 | // If there's any error reading the file, show a message 117 | System.out.println("Error reading the file."); 118 | } 119 | } 120 | } 121 | --------------------------------------------------------------------------------