Estou preso na criação de um loop para ler 6 linhas de um arquivo ao mesmo tempo, economizando cada linha para uma variável para ser usado mais tarde para cálculos

Robbie Beatty:

O projeto é analisar um arquivo de dados de texto e fornecer estatísticas a partir dele. É um arquivo de formato fixo. Nós escrevemos um novo arquivo de formato fixo, utilizando dados que lemos. O que fazemos é ler o primeiro nome, apelido, idade, renda atual, poupança corrente e aumento. Há 606 linhas de código. Então nós temos que ler as primeiras 6 linhas, em seguida, circuito de leitura 6 linhas e armazenar os dados. Então nós temos que encontrar o número de indivíduos por alguns grupos etários (ex 20-29, 30-39, ect). Encontre o min max e média de renda atual. Min máximo e médio do total da poupança. Rendimento Reforma (mensal) min max e média. renda de aposentadoria média por faixa etária (ex, 20-29, 30,39, ect). Tenho sido indo para cima do meu livro (grande java, objetos final) nos últimos 2 horas e agora passando por minhas atribuições passado e eu estou em uma perda completa sobre onde começar. Eu sou um estudante do primeiro ano na universidade para programação java. Nós não usamos matrizes ainda. Onde eu começo sobre este assunto? Eu entendo o que eu preciso fazer, mas eu não entendo leitura de arquivos de qualquer forma. A partir de pesquisas que tenho feito na internet há tantas maneiras diferentes que as pessoas fazem que eu nunca vi antes.

Código atual (Por favor, note que estou muito perdido nesta)

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

public class MidtermProject {

    public static void main(String[] args) throws FileNotFoundException {

    // Declare the file 
    File inputFile = new File ("midterm.txt");
    Scanner in = new Scanner(new File("midterm.txt"));

    // Read first 6 lines 
    String One = in.nextLine();
    String Two = in.nextLine();
    String Three = in.nextLine();
    String Four = in.nextLine();
    String Five = in.nextLine();
    String Six = in.nextLine();

    // Set up loop to read 6 lines at a time  
    }
}
Example of some of the text file 
FirstName
LastName
Age
currentIncome
CurrentSavings
Raise
ROSEMARY
SAMANIEGO
    40
    81539.00
    44293.87
    0.0527
JAMES
BURGESS
    53
    99723.98
    142447.56
    0.0254
MARIBELL
GARZA
    45
    31457.83
    92251.22
    0.0345
Bill Horvath:

Você quer ler este arquivo de seis linhas de cada vez, e fazer cálculos com base no conteúdo de cada conjunto. Primeiro, você precisa de um lugar para colocar os seus valores, e uma classe interna estática seria útil:

private static class EmployeeData {
    final String firstName;
    final String lastName;
    final int age;
    final BigDecimal income;
    final BigDecimal savings;
    final BigDecimal raise;

    public EmployeeData(String firstName, String lastName, int age, BigDecimal income, BigDecimal savings, BigDecimal raise) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.income = income;
        this.savings = savings;
        this.raise = raise;
    }
}

Agora você tem uma estrutura de dados útil para o qual você pode colocar as linhas de seu scanner está lendo. (Note que estamos usando BigDecimals em vez de camas, porque estamos fazendo cálculos financeiros. Que importa .)

    Scanner in = new Scanner(new File("midterm.txt"));

    while (in.hasNext()){

        String firstName = in.nextLine();
        String lastName = in.nextLine();
        int age = in.nextInt();
        BigDecimal income = in.nextBigDecimal();
        BigDecimal savings = in.nextBigDecimal();
        BigDecimal raise = in.nextBigDecimal();

        EmployeeData employeeData = new EmployeeData(firstName, lastName, age, income, savings, raise);
        BigDecimal power = calculatePower(employeeData);
    }

Você está agora configurado para fazer seus cálculos, o que eu iria colocar em métodos apropriadamente nomeados:

private static BigDecimal calculatePower(EmployeeData employeeData){
    int ageDifference = RETIREMENT_AGE - employeeData.age;
    BigDecimal base = employeeData.raise.add(BigDecimal.valueOf(1L));
    BigDecimal baseRaised = BigDecimal.valueOf(Math.pow(base.doubleValue(), ageDifference));
    return employeeData.income.multiply(baseRaised);
}

E você vai precisar especificar as constantes a ser utilizado:

private static final BigDecimal INTEREST = BigDecimal.valueOf(.07);
private static final int RETIREMENT_AGE = 70;
private static final BigDecimal WITHDRAWAL_PERCENT = BigDecimal.valueOf(.04);
private static final BigDecimal SAVINGS_RATE = BigDecimal.valueOf(.15);

Então, o que você acha? Isso lhe dá o suficiente de um começo? Aqui está o programa inteiro até agora; Eu adicionei anotações para explicar mais detalhadamente o que está acontecendo:

import java.math.BigDecimal;
import java.util.*;

// The file name will have to match the class name; e.g. Scratch.java
public class Scratch {

    // These are values that are created when your class is first loaded. 
    // They will never change, and are accessible to any instance of your class.
    // BigDecimal.valueOf 'wraps' a double into a BigDecimal object.
    private static final BigDecimal INTEREST = BigDecimal.valueOf(.07);
    private static final int RETIREMENT_AGE = 70;
    private static final BigDecimal WITHDRAWAL_PERCENT = BigDecimal.valueOf(.04);
    private static final BigDecimal SAVINGS_RATE = BigDecimal.valueOf(.15);

    public static void main(String[] args) {
        // midterm.txt will have to be in the working directory; i.e., 
        // the directory in which you're running the program 
        // via 'java -cp . Scratch'
        Scanner in = new Scanner(new File("midterm.txt"));

        // While there are still more lines to read, keep reading!
        while (in.hasNext()){

            String firstName = in.nextLine();
            String lastName = in.nextLine();
            int age = in.nextInt();
            BigDecimal income = in.nextBigDecimal();
            BigDecimal savings = in.nextBigDecimal();
            BigDecimal raise = in.nextBigDecimal();

            // Put the data into an EmployeeData object
            EmployeeData employeeData = new EmployeeData(firstName, lastName, age, income, savings, raise);
            // Calculate power (or whatever you want to call it)
            BigDecimal power = calculatePower(employeeData);
            System.out.println("power = " + power);
        }
    }

    private static BigDecimal calculatePower(EmployeeData employeeData){
        int ageDifference = RETIREMENT_AGE - employeeData.age;
        // With big decimals, you can't just use +, you have to use 
        // .add(anotherBigDecimal)
        BigDecimal base = employeeData.raise.add(BigDecimal.valueOf(1L));
        BigDecimal baseRaised = BigDecimal.valueOf(Math.pow(base.doubleValue(), ageDifference));
        return employeeData.income.multiply(baseRaised);
    }
    // A static inner class to hold the data
    private static class EmployeeData {

        // Because this class is never exposed to the outside world, 
        // and because the values are final, we can skip getters and 
        // setters and just make the variable values themselves accessible 
        // directly by making them package-private (i.e., there is no '
        // private final' or even 'public final', just 'final')
        final String firstName;
        final String lastName;
        final int age;
        final BigDecimal income;
        final BigDecimal savings;
        final BigDecimal raise;


        public EmployeeData(String firstName, String lastName, int age, BigDecimal income, BigDecimal savings, BigDecimal raise) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.income = income;
            this.savings = savings;
            this.raise = raise;
        }
    }
}

Acho que você gosta

Origin http://10.200.1.11:23101/article/api/json?id=385502&siteId=1
Recomendado
Clasificación