0
I have a huge list of exercises and I only have these two to do last but I can’t do it at all. This I/O thing didn’t get in my head!
Make a program that reads a text file, named "input.txt", composed of integer values and generates a text file, named "output.txt", containing only the prime numbers of the input file.
Make a program that reads the text file generated by the previous program, "output.txt", and check and print on screen, the largest number present in the file and the amount of file numbers that are larger than the average of values contained in the file.
If someone would kindly explain to me how I do this, I am grateful! I did all the other exercises and I would like to get the maximum score by doing all.
That’s what I got from Question 1 code so far:
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class trab2{
public static void main(String [] args){
try{
System.out.println("edite o arquivo entrada.txt");
File entrada = new File("entrada.txt");
Scanner in = new Scanner(entrada);
PrintWriter saida = new PrintWriter("saida.txt");
boolean ehPrimo = true;
int contador = 2;
while(in.hasNextInt()){
int valor = in.nextInt();
while(contador < valor){
if(valor % contador == 0){
ehPrimo = false;
break;
}
contador++;
}
saida.println(valor);
}
saida.close();
in.close();
}catch (FileNotFoundException e){
System.out.println("Arquivo não encontrado. Tente novamente.");
} catch (Exception e){
System.out.println("Erro de execução: " + e.getMessage());
}
}
}
Question two, what I’ve managed to do is this:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class dois{
public static void main(String [] args){
int acumulador = 0;
try{
File saida = new File("saida.txt");
Scanner insaida = new Scanner(saida);
while(insaida.hasNextInt()){
int valor = insaida.nextInt();
if(valor > acumulador){acumulador = valor;}
}
System.out.println("O maior valor no arquivo saida.txt é: " +acumulador);
} catch (FileNotFoundException e){
System.out.println("Arquivo não encontrado. Tente novamente.");
} catch (Exception e){
System.out.println("Erro de execução: " + e.getMessage());
}
}
}
what I can’t do is average the values entered in the file, and how to know how many numbers there are in the file.