java - 我一直坚持创建一个循环来一次读取文件的 6 行,并将每行保存到一个变量中以供稍后用于计算

标签 java text-files filereader filewriter

该项目是分析文本数据文件并提供统计数据。它是一个固定格式的文件。我们使用读取的数据写入一个新的固定格式文件。我们所做的是读取名字、姓氏、年龄、当前收入、当前储蓄和加薪。有606行代码。所以我们必须读取前 6 行,然后循环读取 6 行并存储数据。然后我们必须找到几个年龄组(例如 20-29、30-39 等)的人数。找出当前收入的最小值、最大值和平均值。总节省的最小值、最大值和平均值。退休收入(每月)最小值、最大值和平均值。退休 每个年龄段的平均收入(例如 20-29 岁、30,39 岁等)。 在过去的两个小时里,我一直在复习我的教科书(大java,迟到的对象),并复习我过去的作业,但我完全不知道从哪里开始。我是java编程大学一年级学生。我们还没有使用过数组。我从哪里开始呢?我明白我需要做什么,但我不明白以任何方式从文件中读取。根据我在互联网上所做的研究,人们的做法有很多我以前从未见过的不同方式。

当前代码(请注意我对此非常迷失)

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

最佳答案

您想要一次阅读该文件六行,并根据每组内容进行计算。首先,您需要一个放置值的地方,静态内部类会很有用:

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;
    }
}

现在您有了一个有用的数据结构,您可以将扫描仪正在读取的行放入其中。 (请注意,我们使用 BigDecimals 而不是 double ,因为我们正在进行财务计算。That matters 。)

    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);
    }

您现在已准备好进行计算,我将其放入适当命名的方法中:

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);
}

并且您需要指定正在使用的常量:

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);

那你觉得怎么样?这给了你足够的开始吗?这是到目前为止的整个程序;我添加了注释来更详细地解释发生了什么:

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;
        }
    }
}

关于java - 我一直坚持创建一个循环来一次读取文件的 6 行,并将每行保存到一个变量中以供稍后用于计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60960909/

相关文章:

Java JUnit 测试用例

java - 无限滚动图像 ViewPager

java类读取csv文件而不是文本文件

javascript - 如何在使用 JavaScript 以正确的方向上传之前预览图像?

javascript - 使用 FileReader 时 chrome 中的无效状态错误

java - 如何将监听器放入 web.xml java 中?

java - Google 集合 - 来自 collections.filter 的可修改迭代器?

java - 字长频率

javascript - 非法 base64 字符