Skip to content

Commit e41652e

Browse files
authored
Merge pull request mouredev#6186 from martinbohorquez/java#11
#11 - Java
2 parents 988df62 + dec88fb commit e41652e

File tree

1 file changed

+315
-0
lines changed

1 file changed

+315
-0
lines changed
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
import java.io.*;
2+
import java.util.LinkedList;
3+
import java.util.List;
4+
import java.util.Scanner;
5+
6+
import static java.lang.Double.parseDouble;
7+
8+
/**
9+
* #11 MANEJO DE FICHEROS
10+
*
11+
* @author martinbohorquez
12+
*/
13+
public class martinbohorquez {
14+
private static final FileOperation operation = new FileOperation();
15+
private static final Scanner scanner = new Scanner(System.in);
16+
private static File venta;
17+
18+
public static void main(String[] args) {
19+
String stringFile = "src/data.txt";
20+
String string = """
21+
Nombre: Martin
22+
Edad: 29
23+
Lenguaje de programación: Java
24+
""";
25+
testFile(stringFile, string);
26+
27+
/*
28+
* DIFICULTAD EXTRA
29+
*/
30+
String fileString = "src/venta.txt";
31+
salesManager(fileString);
32+
}
33+
34+
private static void testFile(String stringFile, String string) {
35+
File file = operation.create(stringFile);
36+
operation.write(file, string);
37+
operation.read(file);
38+
operation.delete(file);
39+
}
40+
41+
private static void salesManager(String fileString) {
42+
boolean flag = true;
43+
while (flag) {
44+
System.out.print("""
45+
=========================================
46+
***** PROGRAMA DE GESTIÓN DE VENTAS *****
47+
1. Añadir producto
48+
2. Mostar productos
49+
3. Consultar producto
50+
4. Actualizar producto
51+
5. Borrar producto
52+
6. Calcular venta total
53+
7. Calcular venta por producto
54+
8. Salir
55+
""");
56+
System.out.print("Selecciona la opción (1, 2, 3, 4, 5, 6, 7, 8): ");
57+
String option = scanner.next();
58+
Product product = new Product();
59+
switch (option) {
60+
case "1" -> product.add(fileString);
61+
case "2" -> product.read(venta);
62+
case "3" -> product.consultar(venta);
63+
case "4" -> product.update(venta);
64+
case "5" -> product.delete(venta);
65+
case "6" -> product.calcularVentaTotal(venta);
66+
case "7" -> product.calcularVenta(venta);
67+
case "8" -> {
68+
product.deleteAll(venta);
69+
System.out.println("Saliendo del programa de gestión de ventas!");
70+
flag = false;
71+
}
72+
default -> System.out.println("Debe seleccionar un número de opción válido!");
73+
}
74+
}
75+
}
76+
77+
private static void printFileEmpty() {
78+
System.out.println("El archivo se encuentra vacío, no tiene registros!");
79+
}
80+
81+
private static void printfException(IOException e, String process) {
82+
System.out.printf("Error al '%s' en el archivo: '%s'%n", process, e.getMessage());
83+
}
84+
85+
protected static class FileOperation {
86+
87+
private File create(String string) {
88+
File file = new File(string);
89+
if (file.getParentFile() != null) file.getParentFile().mkdirs();// Crear la carpeta si no existe
90+
return file;
91+
}
92+
93+
private void write(File file, String string) {
94+
try (FileWriter writer = new FileWriter(file, true); Scanner reader = new Scanner(file)) {
95+
writer.append(string).append(System.lineSeparator());
96+
if (!reader.hasNext()) System.out.printf("Archivo '%s' creado!%n", file);
97+
else System.out.printf("Archivo '%s' modificado!%n", file);
98+
} catch (IOException e) {
99+
printfException(e, "escribir");
100+
}
101+
}
102+
103+
private void read(File file) {
104+
if (file == null || file.length() == 0) printFileEmpty();
105+
else {
106+
try (Scanner reader = new Scanner(file)) {
107+
System.out.println("Contenido del archivo: ");
108+
while (reader.hasNext()) System.out.println(reader.nextLine());
109+
} catch (FileNotFoundException e) {
110+
printfException(e, "leer");
111+
}
112+
}
113+
}
114+
115+
private void delete(File file) {
116+
if (file != null && file.delete()) {
117+
if (file.getParentFile() != null && file.getParentFile().delete())
118+
System.out.printf("Folder '\\%s' eliminado correctamente!%n", file.getParentFile().toString());
119+
System.out.printf("Archivo '%s' eliminado correctamente!%n", file);
120+
}
121+
}
122+
}
123+
124+
private static class Product {
125+
private String name;
126+
private Integer quantity;
127+
private Float price;
128+
129+
private static void printProductNotFind(String name) {
130+
System.out.printf("El producto '%s' no se encuentra en el registro de ventas!%n", name);
131+
}
132+
133+
private static void printWrongOperation(String name) {
134+
System.out.printf("La operación '%s' no es válida en este método!%n", name);
135+
}
136+
137+
public Float getPrice() {
138+
return price;
139+
}
140+
141+
public void setPrice(Float price) {
142+
this.price = price;
143+
}
144+
145+
public Integer getQuantity() {
146+
return quantity;
147+
}
148+
149+
public void setQuantity(Integer quantity) {
150+
this.quantity = quantity;
151+
}
152+
153+
public String getName() {
154+
return name;
155+
}
156+
157+
public void setName(String name) {
158+
this.name = name;
159+
}
160+
161+
@Override
162+
public String toString() {
163+
return getName() + ", " + getQuantity() + ", " + getPrice();
164+
}
165+
166+
public void add(String fileString) {
167+
setNameScanner("registrar");
168+
add(fileString, getName());
169+
}
170+
171+
public void add(String fileString, String name) {
172+
if (!contains(venta, name)) {
173+
if (venta == null) venta = operation.create(fileString);
174+
setName(name);
175+
setQuantityAndPriceScan();
176+
operation.write(venta, toString());
177+
} else System.out.printf("El producto %s ya está registrado, usar la opción de actualizar!%n", name);
178+
}
179+
180+
private void read(File venta) {
181+
if (venta == null || venta.length() == 0) printFileEmpty();
182+
else operation.read(venta);
183+
}
184+
185+
private void consultar(File venta) {
186+
if (venta == null || venta.length() == 0) printFileEmpty();
187+
else {
188+
try (Scanner reader = new Scanner(venta)) {
189+
boolean flag = true;
190+
setNameScanner("consultar");
191+
while (flag && reader.hasNext()) {
192+
String productF = reader.nextLine();
193+
String productNameF = productF.split(", ")[0];
194+
if (productNameF.equals(getName())) {
195+
System.out.println(productF);
196+
flag = false;
197+
}
198+
}
199+
if (flag) printProductNotFind(getName());
200+
} catch (FileNotFoundException e) {
201+
printfException(e, "consultar");
202+
}
203+
}
204+
}
205+
206+
private void update(File venta) {
207+
updateOrDelete(venta, "actualizar");
208+
}
209+
210+
public void delete(File venta) {
211+
updateOrDelete(venta, "eliminar");
212+
}
213+
214+
public void calcularVentaTotal(File venta) {
215+
if (venta == null || venta.length() == 0) printFileEmpty();
216+
else {
217+
try (Scanner reader = new Scanner(venta)) {
218+
double calcularTotal = 0.0;
219+
while (reader.hasNext()) {
220+
String[] components = reader.nextLine().split(", ");
221+
calcularTotal += parseDouble(components[1]) * parseDouble(components[2]);
222+
}
223+
System.out.printf("La venta total: %.2f%n", calcularTotal);
224+
} catch (FileNotFoundException e) {
225+
printfException(e, "calcularVentaTotal");
226+
}
227+
}
228+
}
229+
230+
public void calcularVenta(File venta) {
231+
if (venta == null || venta.length() == 0) printFileEmpty();
232+
else {
233+
try (Scanner reader = new Scanner(venta)) {
234+
setNameScanner("consultar");
235+
double calcular = 0.0;
236+
while (reader.hasNext()) {
237+
String[] components = reader.nextLine().split(", ");
238+
if (components[0].equals(getName()))
239+
calcular = parseDouble(components[1]) * parseDouble(components[2]);
240+
}
241+
System.out.printf("La venta total del producto '%s': %.2f%n", getName(), calcular);
242+
} catch (FileNotFoundException e) {
243+
printfException(e, "calcularVenta");
244+
}
245+
}
246+
}
247+
248+
private void deleteAll(File venta) {
249+
operation.delete(venta);
250+
}
251+
252+
private void updateOrDelete(File venta, String operation) {
253+
boolean operationFlag = operation.matches("actualizar|eliminar");
254+
if (!operationFlag) printWrongOperation(operation);
255+
if (venta == null || venta.length() == 0) printFileEmpty();
256+
if (venta != null && operationFlag) {
257+
boolean flag = false;
258+
boolean flagUpdate = operation.equals("actualizar");
259+
List<String> fileContent = new LinkedList<>();
260+
setNameScanner(operation);
261+
try (BufferedReader reader = new BufferedReader(new FileReader(venta))) {
262+
String line;
263+
if (flagUpdate) setQuantityAndPriceScan();
264+
while ((line = reader.readLine()) != null) {
265+
String productNameF = line.split(", ")[0];
266+
if (productNameF.equals(getName())) {
267+
line = flagUpdate ? toString() : null;
268+
flag = true;
269+
}
270+
fileContent.add(line); // Actualizamos la linea de la lista
271+
}
272+
} catch (IOException e) {
273+
printfException(e, operation);
274+
}
275+
if (flag) {
276+
// Reescribimos el archivo con el contenido actualizado
277+
try (BufferedWriter writer = new BufferedWriter(new FileWriter(venta))) {
278+
for (String line : fileContent) {
279+
if (line != null) writer.append(line).append(System.lineSeparator());
280+
}
281+
System.out.printf("El producto '%s' se ha '%so' correctamente!%n",
282+
getName(), operation.substring(0, operation.length() - 2));
283+
} catch (IOException e) {
284+
printfException(e, operation);
285+
}
286+
} else printProductNotFind(getName());
287+
}
288+
}
289+
290+
private void setNameScanner(String operation) {
291+
System.out.printf("Introduce el nombre de producto que desea %s: ", operation);
292+
setName(scanner.next());
293+
}
294+
295+
private void setQuantityAndPriceScan() {
296+
System.out.print("Ingresar la cantidad vendida(unidades): ");
297+
setQuantity(scanner.nextInt());
298+
System.out.print("Ingresar el precio unitario de producto($): ");
299+
setPrice(scanner.nextFloat());
300+
}
301+
302+
private boolean contains(File venta, String productName) {
303+
if (venta == null || venta.length() == 0) return false;
304+
try (Scanner reader = new Scanner(venta)) {
305+
while (reader.hasNext()) {
306+
String productNameF = reader.nextLine().split(", ")[0];
307+
if (productNameF.equals(productName)) return true;
308+
}
309+
} catch (FileNotFoundException e) {
310+
printfException(e, "contains");
311+
}
312+
return false;
313+
}
314+
}
315+
}

0 commit comments

Comments
 (0)