Ejercicio B Completos

This commit is contained in:
2024-05-26 18:43:25 +02:00
parent 03e9a9c007
commit f7a6e9beab
43 changed files with 595 additions and 9 deletions

View File

@@ -0,0 +1,77 @@
package iesthiar;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
/**
* Implementa un programa que muestre por pantalla los valores máximos y mínimos del archivo numeros.txt.
*
*/
public class Ejercicio_B1v2 {
public static void main(String[] args) {
int minimo=Integer.MAX_VALUE;
int maximo=Integer.MIN_VALUE;
// Leer de un fichero. Ruta relativa
File fichero=new File("Documentos/numeros.txt");
// Usamos try-for-resources. No hace falta cerrar, se cierra solo
try (Scanner entrada=new Scanner(fichero)){
// Leemos mientras tengamos datos
while (entrada.hasNext()) {
int numero=entrada.nextInt();
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf("Con Scanner: El mínimo es %d y el máximo es %d%n",minimo,maximo);
// Usando FileReader/BufferedReader
minimo=Integer.MAX_VALUE;
maximo=Integer.MIN_VALUE;
try (BufferedReader br = new BufferedReader(new FileReader("Documentos/numeros.txt"))) {
String linea;
while ((linea = br.readLine()) != null) {
int numero=Integer.parseInt(linea);
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (IOException e) {
System.err.println("Error al leer el archivo: " + e.getMessage());
}
System.out.printf("Con FileReader/BufferedReader: El mínimo es %d y el máximo es %d%n",minimo,maximo);
//Usando nio
minimo=Integer.MAX_VALUE;
maximo=Integer.MIN_VALUE;
Path path = Paths.get("Documentos/numeros.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
int numero=Integer.parseInt(line);
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (IOException ex) {
System.err.println("Error al leer el archivo: " + ex.getMessage());
}
System.out.printf("Con nio: El mínimo es %d y el máximo es %d%n",minimo,maximo);
}
}