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 printing the data on the screen, I observe 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 the registers are updated to 40 when it should go record by record. Not all at once.
What am I doing wrong?
At the request of a user I attach complete code for review:
Part 1 ( Where the data is entered in 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();
}
}
.
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 printing the data on the screen, I observe that it updates all the results to 40:
I do not see anywhere that you assign another value to the variable punts that is not 40. What is linked to what you comment later
-> 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 don't understand where it gets that the first 40, the second 60, the third 30, nor why it would have to store those values, when punts = 40.
This part is also somewhat confusing (for me)
-> ...when it should go record by record.
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 register is always equal to 1? It should not change to go forward in each iteration.
UPDATE
After adding the code from @Paul Vargas, which worked as expected, an error appeared that did not show all the records when querying them, but if they were well stored with Paul's code, it turned out that the error was here:
had to change raf.seek(pos);
Since each record is 48 bytes long, 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 loop can be used
for
.Any read operation (for example,
raf.readInt()
) after the end of the file throws the exceptionEOFException
, since you can't read after the end of the file (although you can write). This can be used to identify the end of file and break the loopfor
.