Código Java para Procesar Embarques y Subidas: Ejemplos Prácticos de Lectura y Escritura de Archivos

Informática y Telecomunicaciones4,58 KB

Código Java para el Procesamiento de Embarques y Subidas

A continuación se presentan dos métodos en Java que procesan archivos de texto para gestionar la ubicación de choferes en una bodega y el control de subidas y bajadas de pasajeros.

Método barco()

Este método lee el archivo Embarque.txt, ubica a cada chofer en una matriz de bodega de 26 filas por 5 columnas y registra en Avisar.txt los choferes mal ubicados, ordenados alfabéticamente.

public static boolean[][] barco() {
    boolean[][] bodega = new boolean[26][5];
    String[][] choferes = new String[26][5];

    ArchivoLectura arch = new ArchivoLectura("Embarque.txt");

    while (arch.hayMasLineas()) {
        String linea = arch.linea();
        String[] datos = linea.split("#");

        int fila = Integer.parseInt(datos[1]) - 1;     // 0 a 25
        int columna = Integer.parseInt(datos[2]) - 1;  // 0 a 4
        String nombreChofer = datos[3];

        bodega[fila][columna] = true;
        choferes[fila][columna] = nombreChofer;
    }

    arch.cerrar();

    // Lista para guardar choferes mal ubicados
    ArrayList choferesMalUbicados = new ArrayList<>();

    for (int j = 0; j < 5; col++) {
        boolean corteEncontrado = false;

        for (int i = 25; i >= 0; fila--) {
            if (bodega[i][j]) {
                if (corteEncontrado) {
                    choferesMalUbicados.add(choferes[i][j]);
                }
            } else {
                corteEncontrado = true;
            }
        }
    }

    // Ordenar alfabéticamente
    Collections.sort(choferesMalUbicados);

    // Grabar archivo
    ArchivoGrabacion errores = new ArchivoGrabacion("Avisar.txt");
    for (String nombre : choferesMalUbicados) {
        errores.grabarLinea(nombre);
    }
    errores.cerrar();

    return bodega;
}

Método proceso()

Este método cruza los datos de Subidas.txt y Bajadas.txt para detectar inconsistencias por asiento y genera el archivo Problemas.txt.

public static void proceso() {
    ArchivoLectura arch = new ArchivoLectura("Subidas.txt");
    int[][] matriz = new int[301][5];

    while (arch.hayMasLineas()) {
        String[] datos = arch.linea().split("#");
        int asiento = Integer.parseInt(datos[0]);
        int cantidadValijas = Integer.parseInt(datos[1]);
        matriz[asiento][0] = cantidadValijas;
    }
    arch.cerrar();

    ArchivoLectura arch2 = new ArchivoLectura("Bajadas.txt");
    while (arch2.hayMasLineas()) {
        String[] datos = arch2.linea().split("#");
        int asiento = Integer.parseInt(datos[0]);
        String estado = datos[1];
        int columna = 1;

        if (estado.equals("R")) {
            columna = 2;
        } else if (estado.equals("M")) {
            columna = 3;
        }

        matriz[asiento][columna] += 1;
    }
    arch2.cerrar();

    ArchivoGrabacion salida = new ArchivoGrabacion("Problemas.txt");
    for (int i = 1; i <= 300; i++) {
        if (matriz[i][0] > 0) {
            int llegaron = matriz[i][1] + matriz[i][2] + matriz[i][3];

            if (matriz[i][0] > llegaron || matriz[i][2] + matriz[i][3] > 0) {
                String linea = "";

                if (i < 10) {
                    linea = linea + "00" + i;
                } else if (i < 100) {
                    linea = linea + "0" + i;
                } else {
                    linea = linea + i;
                }

                linea = linea + "#" + matriz[i][0] + "#" + matriz[i][1] + "#" + matriz[i][2] + "#" + matriz[i][3] + "#" + (matriz[i][0] - llegaron);
                salida.grabarLinea(linea);
            }
        }
    }
    salida.cerrar();
}

Observaciones sobre el código

Se detectaron errores que impiden la compilación y el correcto funcionamiento. En el primer método, los bucles for usan col++ y fila--, variables que no están declaradas ni corresponden a sus contadores (j e i). Además, la llave que cierra el bucle exterior falta en el original, y el método barco() aparece duplicado en el documento. En el segundo método, el bloque for final no cierra correctamente sus llaves. Los fragmentos corregidos arriba mantienen toda la lógica original, pero las correcciones estructurales de los bucles deben revisarse según la intención del algoritmo: el primer bucle interno debería recorrer las filas con i--, no fila--.

Descargar

PDF Word HTML