Java data input and output and data processing

Asked

Viewed 715 times

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!

  1. 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.

  2. 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.

1 answer

7


For question 39, you had only minor errors in your code, see the comments in the code itself:

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

public class Teste{
    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");

            while(in.hasNextInt()){
                //esse valor tem que virar true a cada iteração
                boolean ehPrimo = true; 

                //ele também deve ser resetado para 2 a cada iteração
                int contador = 2;

                int valor = in.nextInt();
                //uma otimização simples é testar o contador até a metade do valor
                //pois nunca um número dividido por outro que seja maior que a sua
                //metade dará resto 0
                while(contador <= valor/2){                    
                    if(valor % contador == 0){
                        ehPrimo = false;
                        break;
                    }
                    contador++;
                }
                //tem que ter o if aqui para se certificar de que ele passou no teste
                if(ehPrimo) {           
                    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());
        }
    }
}

To question 40:

the largest number present in the archive

you need to define a variable with the lowest possible value, for example:

int max = Integer.MIN_VALUE;

And iterate over all items in your text file whenever the current iteration file is larger than the value in max, you assign to max that new value:

and the amount of file numbers that are larger than the average of values contained in the file.

First of all you need to average. I believe that it is best to iterate item by item and add up the amount of items traveled and the sum of their value. Then you start iterating again from the beginning, checking how many values are greater than the average.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.