Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java OOP Fundamentals: String Parsing, File I/O, and Interactive Console Applications

Tech May 14 1

Theoretical Foundation

This week's study focused on consolidating core Java concepts from the introductory modules. Key areas included Java's architecture-neutral design, standardized coding conventions, and the practical workflow within the Eclipse IDE. A significant portion of the review targeted foundational syntax, with particular emphasis on operator precedence, control flow structures, and standard input/output mechanisms. Analyzing JDK source code provided valuable insights into industry-standard formatting and object-oriented design patterns.

Lab Objectives

  • Navigate the Eclipse integrated devleopment environment efficiently.
  • Adapt to automated grading platforms and understand their compilation/runtime constraints.
  • Implement basic Java syntax including clases, methods, and control structures.
  • Design applications featuring a single entry point with modular method decomposition.

Exercise 1: Identity Card Date Extraction

The first task required parsing an 18-character national identifier string to extract the birth date segment and format it as YYYY-MM-DD. The specification mandated using Scanner.nextLine() to safely handle console input without tokenization issues.

import java.util.Scanner;

public class IdentifierProcessor {
    
    public static void main(String[] args) {
        Scanner consoleInput = new Scanner(System.in);
        System.out.print("Enter 18-digit identifier: ");
        String rawInput = consoleInput.nextLine().trim();
        
        if (validateLength(rawInput)) {
            String formattedDate = extractBirthDate(rawInput);
            System.out.println("Formatted Date: " + formattedDate);
        } else {
            System.out.println("Invalid input length.");
        }
        consoleInput.close();
    }

    private static boolean validateLength(String input) {
        return input != null && input.length() == 18;
    }

    private static String extractBirthDate(String identifier) {
        String yearPart = identifier.substring(6, 10);
        String monthPart = identifier.substring(10, 12);
        String dayPart = identifier.substring(12, 14);
        return String.format("%s-%s-%s", yearPart, monthPart, dayPart);
    }
}

Exercise 2: Student Record Lookup System

The second exercise involved reading a plain text file containing student IDs and names, loading them into memory, and implementing a bidirectional search mechanism. The application required a console-based menu allowing users to query by name or by ID.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class StudentDirectory {
    
    private final Map<string string=""> idToNameMap = new HashMap<>();
    private final Map<string string=""> nameToIdMap = new HashMap<>();
    
    public void loadRecords(String filePath) {
        Path documentPath = Paths.get(filePath);
        try (BufferedReader reader = new BufferedReader(new FileReader(documentPath.toFile()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] components = line.trim().split("\\s+");
                if (components.length >= 2) {
                    String identifier = components[0];
                    String fullName = components[1];
                    idToNameMap.put(identifier, fullName);
                    nameToIdMap.put(fullName, identifier);
                }
            }
        } catch (IOException exception) {
            System.err.println("File access error: " + exception.getMessage());
        }
    }

    public String lookupById(String searchId) {
        return idToNameMap.getOrDefault(searchId, "Record not found.");
    }

    public String lookupByName(String searchName) {
        return nameToIdMap.getOrDefault(searchName, "Record not found.");
    }

    public static void main(String[] args) {
        StudentDirectory directory = new StudentDirectory();
        directory.loadRecords("student_data.txt");
        
        Scanner terminal = new Scanner(System.in);
        int userChoice;
        
        do {
            System.out.println("\n--- Student Lookup Menu ---");
            System.out.println("1. Search by Name");
            System.out.println("2. Search by ID");
            System.out.println("3. Exit");
            System.out.print("Select option: ");
            
            if (terminal.hasNextInt()) {
                userChoice = terminal.nextInt();
                terminal.nextLine(); 
                
                switch (userChoice) {
                    case 1 -> {
                        System.out.print("Enter full name: ");
                        String query = terminal.nextLine();
                        System.out.println("Result: " + directory.lookupByName(query));
                    }
                    case 2 -> {
                        System.out.print("Enter student ID: ");
                        String query = terminal.nextLine();
                        System.out.println("Result: " + directory.lookupById(query));
                    }
                    case 3 -> System.out.println("Terminating session.");
                    default -> System.out.println("Invalid selection.");
                }
            } else {
                System.out.println("Please enter a numeric value.");
                terminal.nextLine();
                userChoice = 0;
            }
        } while (userChoice != 3);
        
        terminal.close();
    }
}</string></string>

Development Insights & Platform Adaptation

Transitioning from local development environments to automated assessment platforms revealed several critical differences. Code that executes flawless in Eclipse may fail on grading systems due to strict class naming conventions, package declarations, or input buffering behaviors. This discrepancy highlighted the importance of adhering to platform-specific constraints and avoiding package declarations in submitted code unless explicitly required.

Furthermore, relying solely on theoretical reading or copying examples from textbooks proved insufficient for handling real-world scenarios. Independent problem-solving requires a deeper grasp of syntax nuances and memory management. The file I/O exercise demonstrated the value of using data structures like HashMap over linear iteration for search operations, significantly improving performance and code readability.

Iterative practice and exposure to diverse coding challenges remain essential for solidifying foundational concepts. Each exercise uncovers gaps in understanding, reinforcing the necessity of hands-on implementation, systematic debugging, and continuous refinement of coding standards.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.