Modify "Points" binary file (modify by SEEK)

4

I need help with the following piece of code:

 case 1:
System.out.println("Actualizar Puntos");
int registro = 1;
// Nuevos puntos (entrada del usuario)
punts = 40;
// Posición donde comienza el registro
int pos = 48 * (registro - 1);
// Mover a la posición donde empieza el dato
pos += 4 + 20 + 20;
raf.seek(pos);
raf.writeInt(punts);              

   break;

When I print the data on the screen I see that it updates all the results to 40:

ID: 50
Nombre Instituto: inst1
Nombre Equipo: equi1
Puntos: 40

ID: 600
Nombre Instituto: inst2
Nombre Equipo: equip2
Puntos: 40

ID: 6000
Nombre Instituto: inst3
Nombre Equipo: equip3
Puntos: 40

Each record should have a different number of points. For example: the first 40 points, the second 60 points, the third 30 points, etc.

The problem is that all records are updated to 40 when you should go record by record. Not all at once.

What am I doing wrong?

At the request of an attached user, complete code for review:

Part 1 (Where data is entered into the binary file)

/**
 * OPCIO 1  ACTIVITAT 2
 */
package activitat2;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
/**
 * ACTIVITAT 2 EAC 6
 * @author Montse
 */
    public class Opcio1{
    /**
     * En aquesta activitat la número 2 farem:
     * Introduir instituts
     * Listar instituts introduïts
     * Sortir
     * Tornar al menú principal
     * @throws FileNotFoundException
     * @throws IOException
     */

    static void IntroduirInstituts() throws FileNotFoundException, IOException{
        RandomAccessFile raf;
        raf = new RandomAccessFile("Partides.dat", "rw");

        System.out.println("HAS ESCOLLIT OPCIÓ 1");
        System.out.println("--------------------------------");
        System.out.println("Institutos que participarán en infoguardians");
        System.out.println("1-Registrar los datos de los institutos ");
        System.out.println("2-Listar todos los institutos");
        System.out.println("3-Volver al menú principal");
        System.out.println("4- Salir");
        System.out.println("Escoje una opción");

        Scanner lector = new Scanner(System.in);

        int punts       = 0;
        int enterLlegit = 0;
        boolean llegit  = false;

        while(!llegit){
            llegit = lector.hasNextInt();
            if (llegit){

                enterLlegit = lector.nextInt();

                switch (enterLlegit){
                case 1:
                    System.out.println("Registra los datos de los institutos:");
                    System.out.println("Quantos institutos participan en el concurso?");
                    boolean leido = false;
                    while(!leido){

                        leido = lector.hasNextInt();
                        if (leido){

                            int enterLlegit2 = lector.nextInt();
                            System.out.println("Numero total de centros: "+enterLlegit2);
                            System.out.println("El fitxer s'ha creat. Accés directe");
                            for (int j = 0, pos = 0; j < enterLlegit2; j++){
                                int i = 0;
                                i = enterLlegit2;
                                if(enterLlegit2 > 0){

                                    System.out.println("-------------------------------------");
                                    System.out.println("Introduce la info sobre el instituto:");
                                    System.out.println("-------------------------------------");
                                    System.out.println("Id?");

                                    int idInst = lector.nextInt();

                                    System.out.println("Nom Institut:");

                                    String nomInst = lector.next();

                                    System.out.println("Nom Equip:");

                                    String nomEqui = lector.next();

                                    System.out.println();

                                    System.out.println("------------------------------------------");
                                    System.out.println("::INFORMACIÓN SOBRE CENTRO INSCRITO::");
                                    System.out.println("------------------------------------------");
                                    System.out.println("Id: " +idInst);
                                    System.out.println("Nom Institut: "+nomInst);
                                    System.out.println("Equip: "+nomEqui);
                                    System.out.println("Punts: "+punts);
                                    System.out.println();


                                    raf.seek(pos);
                                    raf.writeInt(idInst);
                                    pos +=4;
                                    raf.seek(pos);
                                    raf.writeUTF(nomInst);
                                    pos +=20;
                                    raf.seek(pos);
                                    raf.writeUTF(nomEqui);
                                    pos+=20;
                                    raf.seek(pos);
                                    raf.writeInt(punts);
                                    pos +=4;

                                }
                            }

                        }else {
                            System.out.println("No has escrito un entero, vuelve a intentarlo");
                            lector.next();
                        }
                    }

                    break;
                case 2:
                    System.out.println("------------------------------------");
                    System.out.println("HAS ESCOGIDO LISTAR LOS INSTITUTOS");
                    System.out.println("------------------------------------");
                    for (int pos = 0;;){

                        try
                        {
                            raf.seek(pos);

                            System.out.println("ID: " +raf.readInt());
                            pos += 4;

                            raf.seek(pos);
                            System.out.println("Nombre Instituto: "+raf.readUTF());
                            pos += 20;

                            raf.seek(24);
                            System.out.println("Nombre Equipo: "+raf.readUTF());
                            pos += 20;

                            raf.seek(44);
                            System.out.println("Puntos: "+raf.readInt());
                            pos += 4;

                            System.out.println();
                        }
                        catch (EOFException e)
                        {
                            // Fin de archivo
                            break;
                        }
                    }
                case 3:
                    System.out.println("TORNAR AL MENÚ PRINCIPAL::::");
                    MenuPrincipal.EscollirOpcio();

                case 4:
                    System.out.println("Hasta la próxima!");
                    break;
                default:
                    System.out.println("No has escrito una opción válida");
                    System.out.println("Fin del programa");
                    break;
                }

            }else {

                System.out.println("No has escrito un entero, vuelve a intentarlo");
                lector.next();
            }
        }
        lector.nextLine();


    }
}

Part 2 of the code where I want to modify:

/**
 * OPCIO 2  ACTIVITAT 3
 */
package activitat2;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
/**
 *
 * @author Montse
 */


 public class Opcio2 {
    /**
     * En aquesta clase farem les demandes de l'activitat 2
     * @throws FileNotFoundException
     */
    static void ActualitzarInstituts() throws FileNotFoundException, IOException {
        RandomAccessFile raf;
        raf = new RandomAccessFile("Partides.dat", "rw");

        System.out.println("HAS ESCOLLIT OPCIÓ 2");
        System.out.println("--------------------------------");
        System.out.println("Institutos que participarán en infoguardians");
        System.out.println("1-Actualizar Puntos");
        System.out.println("2- Salir");
        System.out.println("3- Volver al menú principal");
        System.out.println("Escoje una opción");

        Scanner lector = new Scanner(System.in);

        int punts       = 0;
        int enterLlegit = 0;
        boolean llegit  = false;

        while(!llegit) {

            llegit = lector.hasNextInt();

            if (llegit) {

                enterLlegit = lector.nextInt();

                switch (enterLlegit) {
                case 1:
                    System.out.println("Actualizar Puntos");
                    // Primero enseñaremos los intitutos que tenemos registrados
                    System.out.println("LOS CENTROS INTRODUCIDOS SÓN:::::::");
                    System.out.println("-----------------------------------");

                    for (int pos = 0;;){

                        try
                        {
                            raf.seek(pos);

                            System.out.println("ID: " +raf.readInt());
                            pos += 4;

                            raf.seek(pos);
                            System.out.println("Nombre Instituto: "+raf.readUTF());
                            pos += 20;

                            raf.seek(24);
                            System.out.println("Nombre Equipo: "+raf.readUTF());
                            pos += 20;

                            raf.seek(44);
                            System.out.println("Puntos: "+raf.readInt());
                            pos += 4;

                            System.out.println();
                        }
                        catch (EOFException e)
                        {
                            // Fin de archivo

                        }
                        System.out.println("Actualizar Puntos");
                        int registro = 1;
                        // Nuevos puntos (entrada del usuario)
                        punts = 40;
                        // Posición donde comienza el registro
                        pos = 48 * (registro - 1);
                        // Mover a la posición donde empieza el dato
                        pos += 4 + 20 + 20;
                        raf.seek(pos);
                        raf.writeInt(punts);

                        break;
                    }

                case 2:
                    System.out.println("Hasta la próxima!");
                    break;
                default:
                    System.out.println("No has escrito una opción válida");
                    System.out.println("Fin del programa");
                    break;
                }

            }else {
                System.out.println("No has escrito un entero, vuelve a intentarlo");
                lector.next();
            }
        }
        lector.nextLine();


    }
}
    
asked by Montse Mkd 07.01.2016 в 15:05
source

2 answers

2

Since each record has a length of 48 bytes, of which there are several in the file, then to modify the points in each of them (each with a different score, of course), a cycle for can be used %.

for (int registro = 1;; registro++) {
    int pos = 48 * (registro - 1);
    try {
        System.out.printf("Registro #%02d%n", registro);
        pos += 4 + 20 + 20;

        // Lectura
        raf.seek(pos);
        System.out.printf("Puntos actuales: %d%n", raf.readInt());

        // Escritura
        System.out.print("Introducir puntos: ");
        int puntos = scanner.nextInt();
        raf.seek(pos);
        raf.writeInt(puntos);
    } catch (EOFException e) {
        break;
    }
}

Any read operation (for example, raf.readInt() ) after the end of the file throws the exception EOFException , because it can not be read after the end of the file (although it does write). This can be used to identify the end of the file and break the cycle for .

    
answered by 07.01.2016 / 19:59
source
3
 case 1:
System.out.println("Actualizar Puntos");
int registro = 1;
// Nuevos puntos (entrada del usuario)
punts = 40;
// Posición donde comienza el registro
int pos = 48 * (registro - 1);
// Mover a la posición donde empieza el dato
pos += 4 + 20 + 20;
raf.seek(pos);
raf.writeInt(punts);              

   break;

.

ID: 50
Nombre Instituto: inst1
Nombre Equipo: equi1
Puntos: 40

ID: 600
Nombre Instituto: inst2
Nombre Equipo: equip2
Puntos: 40

ID: 6000
Nombre Instituto: inst3
Nombre Equipo: equip3
Puntos: 40

I do not know if this will be a true answer to what you are looking for, but I will tell you what I see as I understand what you are asking:

You say

- > When I print the data on the screen I see that it updates all the results to 40:

//..
// Nuevos puntos (entrada del usuario)
punts = 40;
//..
raf.writeInt(punts);
//..

I do not see in any place that you assign another value to the variable punts other than 40. What is linked to what you comment afterwards

- > Each record should have a different number of points. For example: the first 40 points, the second 60 points, the third 30 points, etc.

I do not understand where you get the first 40, the second 60, third 30, or why you would have to store those values, when punts = 40.

This part is also somewhat confusing (for me)

- > ... when I should go register by register.

//..
viendo esto -> int registro = 1;
y esto      -> int pos 48 * (registro -1);

What I imagine you want to do is jump from one position to another, which has the same internal structure to change the bits / content of that position. If so, why is registration always equal to 1? It should not change to move forward in each iteration.

UPDATE

After adding the code of @Paul Vargas, which worked as expected, an error appeared that did not show all the records when consulting them but if they were stored well with Paul's code, it turned out that the error was here:

raf.seek(24); 
System.out.println("Nombre Equipo: "+raf.readUTF()); 
pos += 20; 

raf.seek(44); 
System.out.println("Puntos: "+raf.readInt()); 
pos += 4; 

had to change raf.seek (pos);

    
answered by 07.01.2016 в 17:57