Java - Altas, bajas, ...

 
Vista:
sin imagen de perfil
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Altas, bajas, ...

Publicado por Victor (18 intervenciones) el 15/10/2021 19:14:47
Estoy atascado con este ejercicio de acceso a datos y es que me da errores que por mas que lo intento y horas que hecho no consigo solucionar por si alguien puede echar un cable pls. El enunciado es el siguiente:
- Crea un programa que sea capaz de gestionar altas, bajas y modificaciones de la clase Coche adjunta.
Se deberá utilizar un fichero como sistema para mantener la permanencia de los datos. Gestiona
las opciones a través de un menú.
Estas son mis dos clases:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package practicaEvaluable1;
 
import java.io.Serializable;
 
/*
 * Crea un programa que sea capaz de gestionar altas, bajas y modificaciones de la clase Coche adjunta.
 * Se deberá utilizar un fichero como sistema para mantener la permanencia de los datos. Gestiona
 * las opciones a través de un menú.
 */
 
public class Coche implements Serializable {
 
	/**
	 * Se añade el ID de serialización para la deserialización
	 */
	public static final long serialVersionUID = 1L;
    String marca;
	String modelo;
	int unidades;
	double precio;
 
	/**
	 * Constructor
	 * @param marca
	 * @param modelo
	 * @param unidades
	 * @param precio
	 */
	public Coche (String marca, String modelo, int unidades, double precio) {
		this.marca=marca;
		this.modelo=modelo;
		this.unidades=unidades;
		this.precio=precio;
	}
 
	/**
	 * Constructor
	 */
	public Coche () {
		this.marca=null;
	}
 
	//getters y setters
	/**
	 *
	 * @return
	 */
	public String getMarca() {
		return marca;
	}
 
	/**
	 *
	 * @param marca
	 */
	public void setMarca(String marca) {
		this.marca = marca;
	}
 
	/**
	 *
	 * @return
	 */
	public String getModelo() {
		return modelo;
	}
 
	/**
	 *
	 * @param modelo
	 */
	public void setModelo(String modelo) {
		this.modelo = modelo;
	}
 
	/**
	 *
	 * @return
	 */
	public int getUnidades() {
		return unidades;
	}
 
	/**
	 *
	 * @param unidades
	 */
	public void setUnidades(int unidades) {
		this.unidades = unidades;
	}
 
	/**
	 *
	 * @return
	 */
	public double getPrecio() {
		return precio;
	}
 
	/**
	 *
	 * @param precio
	 */
	public void setPrecio(double precio) {
		this.precio = precio;
	}
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package practicaEvaluable1;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
 
public class ProgramaPrincipal  implements Serializable {
 
	public static void main(String[] args) throws IOException, ClassNotFoundException {
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
		boolean programaActivo = true;
		int opcion;
 
		System.out.println("Menú de gestión de lista, altas, bajas y modificaciones");
 
		//ObjectOutputStream
		File file = new File("C:\\Users\\vdiaz\\OneDrive\\Escritorio\\DAM2\\Acceso a datos\\Primera evaluación\\ficherosAD\\Coche.bin");
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		do {
			System.out.println("Escoge la opción que quiera realizar:");
			System.out.println("1. Altas");
			System.out.println("2. Bajas");
			System.out.println("3. Modificaciones");
			System.out.println("4. Consultar");
			System.out.println("5. Salir");
			opcion=sc.nextInt();
 
			if(opcion == 1) {
				altaCoche(file);
			}else if (opcion == 2) {
				bajaCoche(file);
			}else if (opcion == 3) {
				modificacionCoche(file);
			}else if (opcion == 4) {
				listaCoche(file);
			}else if (opcion == 5) {
				programaActivo = false;
			}else {
				System.out.println("No has escogido correctamente.");
			}
		}while (programaActivo);
 
		oos.close();
 
		//ObjectInputStream
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
 
		try {
			while(true) {
				ArrayList<Coche> readObject = (ArrayList<Coche>) ois.readObject();
				coches = readObject;
			}
		} catch (ClassNotFoundException | IOException e) {
		}
 
		ois.close();
 
	}
 
	public static void altaCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Aqui dará de alta al coche.");
 
		System.out.println("Introduce el nombre del coche: ");
		String marca = sc.next();
		System.out.println("Introduce el modelo: ");
		String modelo = sc.next();
		System.out.println("Introduce las unidades: ");
		int unidades = Integer.parseInt(sc.next());
		System.out.println("Introduce el precio: ");
		double precio = Double.parseDouble(sc.next());
 
		Coche c1 = new Coche(marca,modelo,unidades, precio);
 
		for(int i=0; i<marca.length(); i++) {
			c1 = new Coche(marca,modelo, unidades, precio);
			oos.writeObject(c1);
		}
 
		coches.add(c1);
 
	}
 
	public static void bajaCoche(File file)  throws IOException{
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Aqui dará de baja al coche.");
 
		String marca= sc.next();
 
		Iterator<Coche> it = coches.iterator();
		while(it.hasNext()) {
			Coche c1 = it.next();
			if(c1.getMarca().equals(marca));
				it.remove();
		}
 
	}
 
	public static void modificacionCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Elige el nombre del coche que quieras modificar (elige unicamente la marca)");
		String marca = sc.next();
 
		System.out.println("Introduce los datos del nuevo coche.");
		System.out.println("Nueva marca: ");
		String marca2 = sc.next();
		System.out.println("Nuevo modelo: ");
		String modelo2 = sc.next();
		System.out.println("Nuevas unidades: ");
		int unidades2 = Integer.parseInt(sc.next());
		System.out.println("Nuevo precio: ");
		Double precio2 = Double.parseDouble(sc.next());
 
		Iterator<Coche> it = coches.iterator();
 
		while (it.hasNext()) {
			Coche c1 = it.next();
			if (c1.getMarca().equals(marca)) {
				c1.setMarca(marca2);
				c1.setModelo(modelo2);
				c1.setPrecio(precio2);
				c1.setUnidades(unidades2);
			}
		}
 
	}
 
	public static void listaCoche(File file)  throws IOException{
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Listado de coches.");
		for (Coche c1: coches) {
			System.out.println("Marca: " + c1.getMarca() + "\nModelo: " + c1.getModelo() + "\nUnidades: " + c1.getUnidades() + "\nPrecio: " + c1.getPrecio());
		}
 
	}
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Altas, bajas, ...

Publicado por Santiago (25 intervenciones) el 16/10/2021 10:54:25
Hola:

Voy a ver si puedo ayudarte poco a poco.

Primero, no entiendo qué quieres hacer aquí:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
                // Aquí Creas un coche, que en realidad no es un coche sino un objeto Coche que es una cantidad "N" de un modelo y marca.
		Coche c1 = new Coche(marca,modelo,unidades, precio);
 
                // Aquí pretendes escribir en un fichero tantos coches como se haya indicado ("N"), pero en lugar de hacer un bucle "for" sobre
                // la variable "unidades" lo haces sobre la longitud del nombre de la marca :(. Es decir, si indica que hay 1 unidad de un Seat,
                // almacenas en el fichero 4 coches. Creo que no tiene sentido.
		for(int i=0; i<marca.length(); i++) {
                        // Aquí "sobreescribes" el Coche c1 anterior constantemente
			c1 = new Coche(marca,modelo, unidades, precio);
			oos.writeObject(c1);
		}
 
                // Aquí guardas EL ÚLTIMO COCHE de los "N" que has escrito en el fichero en una matriz que al salir del método, deja de existir,
		coches.add(c1);

Para mi, y es una opinion personal, deberías plantear esto de la siguiente forma:

- Inicio del programa
- abro el fichero y leo el contenido del mismo cargándolo en el ArrayList
- se ejecutan las opciones de menú que quiera el usuario actuando SÓLO sobre el ArrayList
- cuando se selecciona "5.- Salir", guardo el ArrayList en el fichero.

Es decir, sólo accedo al fichero al principio y al final del programa, El resto del tiempo actúo sobre el ArrayList.

Te copio parte de cómo debería ser (a mi entender):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package practicaEvaluable1;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
 
public class ProgramaPrincipal  implements Serializable {
 
	static final String fichero = "D:\\Curso de programacion Java\\workbench\\LWP\\Coche.bin";
	static ArrayList<Coche> coches = new ArrayList<Coche>();
 
	public static void main(String[] args) throws IOException, ClassNotFoundException {
 
		Scanner sc = new Scanner(System.in);
		boolean programaActivo = true;
		int opcion;
		File file = new File(fichero);
 
		// Cargamos el ArrayList con el contenido del fichero
		leeCoches();
 
		System.out.println("Menú de gestión de lista, altas, bajas y modificaciones");
 
		do {
			System.out.println("Escoge la opción que quiera realizar:");
			System.out.println("1. Altas");
			System.out.println("2. Bajas");
			System.out.println("3. Modificaciones");
			System.out.println("4. Consultar");
			System.out.println("5. Salir");
			opcion=sc.nextInt();
 
			if(opcion == 1) {
				altaCoche(file);
			}else if (opcion == 2) {
				bajaCoche(file);
			}else if (opcion == 3) {
				modificacionCoche(file);
			}else if (opcion == 4) {
				listaCoche(file);
			}else if (opcion == 5) {
				programaActivo = false;
			}else {
				System.out.println("No has escogido correctamente.");
			}
		}while (programaActivo);
 
		// Guardamos el ArrayList en el fichero
		guardaCoches();
 
	}
 
	// Cargamos el ArrayList con el contenido del fichero
	private static boolean leeCoches() {
 
		ObjectInputStream ois;
		try {
			ois = new ObjectInputStream(new FileInputStream(fichero));
 
			Object c = ois.readObject();
 
			// Mientras haya objetos
			while (c!=null)
			{
			    if (c instanceof Coche)
			        coches.add((Coche)c);
			    c = ois.readObject();
			}
			ois.close();
			return true;
		} catch (ClassNotFoundException | IOException e) {
			return false;
		}
	}
 
	// Guardamos el ArrayList en el fichero
	private static boolean guardaCoches() {
 
		ObjectOutputStream oos;
		try {
			// Abrimos el fichero
			oos = new ObjectOutputStream(new FileOutputStream(fichero));
 
			// Escribimos el ArrayList al salir del programa
			for (Coche c : coches) {
				oos.writeObject(c);
			}
 
			//Cerramos el fichero
			oos.close();
			return true;
		}catch(Exception ex) {
			return false;
		}
 
	}
 
	public static void altaCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Aqui dará de alta al coche.");
 
		System.out.println("Introduce el nombre del coche: ");
		String marca = sc.next();
		System.out.println("Introduce el modelo: ");
		String modelo = sc.next();
		System.out.println("Introduce las unidades: ");
		int unidades = Integer.parseInt(sc.next());
		System.out.println("Introduce el precio: ");
		double precio = Double.parseDouble(sc.next());
 
		// Creamos un objeto "Coche"
		Coche c1 = new Coche(marca,modelo,unidades, precio);
 
		// La escritura la hacemos al salir del programa, escribiendo todo el ArrayList
//		for(int i=0; i<marca.length(); i++) {
//			c1 = new Coche(marca,modelo, unidades, precio);
//			oos.writeObject(c1);
//		}
 
		// Lo añadimos al ArrayList
		coches.add(c1);
 
	}
 
...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Altas, bajas, ...

Publicado por Victor (18 intervenciones) el 16/10/2021 21:27:29
Vale un poco mejor desde luego porque está mas organizado y tiene más sentido como lo haces. Sin embargo, no entiendo bien del todo porque pones este for entre comentarios y como lo tengo que usar:
1
2
3
4
5
// La escritura la hacemos al salir del programa, escribiendo todo el ArrayList
//		for(int i=0; i<marca.length(); i++) {
//			c1 = new Coche(marca,modelo, unidades, precio);
//			oos.writeObject(c1);
//		}

No entiendo del todo como hacer para que se me guarde el array de una alta de un coche escrito por consola en el menú. Este sería mi codigo actual, pero como vas a ver tampoco tiene gran cambio del todo y sigue sin cumplir su función.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package practicaEvaluable01;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
 
import practicaEvaluable1.Coche;
 
public class ProgramaPrincipal  implements Serializable {
 
	static final String fichero = "C:\\Users\\vdiaz\\OneDrive\\Escritorio\\DAM2\\Acceso a datos\\Primera evaluación\\ficherosAD\\Coche.bin";
	static ArrayList<Coche> coches = new ArrayList<Coche>();
 
	public static void main(String[] args) throws IOException, ClassNotFoundException {
 
		Scanner sc = new Scanner(System.in);
		boolean programaActivo = true;
		int opcion;
		File file = new File(fichero);
 
		// Cargamos el ArrayList con el contenido del fichero
		leeCoches();
 
		System.out.println("Menú de gestión de lista, altas, bajas y modificaciones");
 
		do {
			System.out.println("Escoge la opción que quiera realizar:");
			System.out.println("1. Altas");
			System.out.println("2. Bajas");
			System.out.println("3. Modificaciones");
			System.out.println("4. Consultar");
			System.out.println("5. Salir");
			opcion=sc.nextInt();
 
			if(opcion == 1) {
				altaCoche(file);
			}else if (opcion == 2) {
				bajaCoche(file);
			}else if (opcion == 3) {
				modificacionCoche(file);
			}else if (opcion == 4) {
				listaCoche(file);
			}else if (opcion == 5) {
				programaActivo = false;
			}else {
				System.out.println("No has escogido correctamente.");
			}
		}while (programaActivo);
 
		// Guardamos el ArrayList en el fichero
		guardaCoches();
 
	}
 
	// Cargamos el ArrayList con el contenido del fichero
	private static boolean leeCoches() {
 
		ObjectInputStream ois;
		try {
			ois = new ObjectInputStream(new FileInputStream(fichero));
 
			Object c = ois.readObject();
 
			// Mientras haya objetos
			while (c!=null)
			{
			    if (c instanceof Coche)
			        coches.add((Coche)c);
			    c = ois.readObject();
			}
			ois.close();
			return true;
		} catch (ClassNotFoundException | IOException e) {
			return false;
		}
	}
 
	// Guardamos el ArrayList en el fichero
	private static boolean guardaCoches() {
 
		ObjectOutputStream oos;
		try {
			// Abrimos el fichero
			oos = new ObjectOutputStream(new FileOutputStream(fichero));
 
			// Escribimos el ArrayList al salir del programa
			for (Coche c : coches) {
				oos.writeObject(c);
			}
 
			//Cerramos el fichero
			oos.close();
			return true;
		}catch(Exception ex) {
			return false;
		}
 
	}
 
	public static void altaCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Aqui dará de alta al coche.");
 
		System.out.println("Introduce el nombre del coche: ");
		String marca = sc.next();
		System.out.println("Introduce el modelo: ");
		String modelo = sc.next();
		System.out.println("Introduce las unidades: ");
		int unidades = Integer.parseInt(sc.next());
		System.out.println("Introduce el precio: ");
		double precio = Double.parseDouble(sc.next());
 
		// Creamos un objeto "Coche"
		Coche c1 = new Coche(marca,modelo,unidades, precio);
 
		// La escritura la hacemos al salir del programa, escribiendo todo el ArrayList
		for(int i=0; i<marca.length(); i++) {
			c1 = new Coche(marca,modelo, unidades, precio);
			oos.writeObject(c1);
		}
 
		// Lo añadimos al ArrayList
		coches.add(c1);
 
	}
 
	public static void bajaCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Aqui dará de baja al coche.");
 
		String marca= sc.next();
 
		Iterator<Coche> it = coches.iterator();
		while(it.hasNext()) {
			Coche c1 = it.next();
			if(c1.getMarca().equals(marca));
				it.remove();
		}
 
	}
 
 
	public static void modificacionCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Elige el nombre del coche que quieras modificar (elige unicamente la marca)");
		String marca = sc.next();
 
		System.out.println("Introduce los datos del nuevo coche.");
		System.out.println("Nueva marca: ");
		String marca2 = sc.next();
		System.out.println("Nuevo modelo: ");
		String modelo2 = sc.next();
		System.out.println("Nuevas unidades: ");
		int unidades2 = Integer.parseInt(sc.next());
		System.out.println("Nuevo precio: ");
		Double precio2 = Double.parseDouble(sc.next());
 
		Iterator<Coche> it = coches.iterator();
 
		while (it.hasNext()) {
			Coche c1 = it.next();
			if (c1.getMarca().equals(marca)) {
				c1.setMarca(marca2);
				c1.setModelo(modelo2);
				c1.setPrecio(precio2);
				c1.setUnidades(unidades2);
			}
		}
 
	}
 
	public static void listaCoche(File file)  throws IOException {
 
		Scanner sc = new Scanner(System.in);
 
		ArrayList<Coche> coches = new ArrayList<Coche>();
 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 
		System.out.println("Listado de coches.");
		for (Coche c1: coches) {
			System.out.println("Marca: " + c1.getMarca() + "\nModelo: " + c1.getModelo() + "\nUnidades: " + c1.getUnidades() + "\nPrecio: " + c1.getPrecio());
		}
 
	}
 
}
Siento las molestias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Altas, bajas, ...

Publicado por Victor (18 intervenciones) el 17/10/2021 14:32:17
Vale perdona ya nada, conseguí hacer que ya fuera bien y sin errores guardándome los datos del fichero correctamente y lo entiendo ya perfectamente. Un saludo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar