将用户输入并存储到文件中的数组

时间:2015-04-06 17:05:54

标签: java class methods fileoutputstream bufferedinputstream

我试图将多个用户输入存储为基于字节的文件,然后获取文件编号并在我编写的程序中使用它们进行计算。我开始将字符串转换为double,但是我遇到了读取值并在calc方法中进行修改的问题。我发现我想使用fileOutputStream但不知道如何合并到代码中。任何指导将不胜感激。请参阅代码以供参考:

import java.util.Scanner;
import java.io.*;

public class BankApp {
    public static void main (String [] args) throws IOException{

        double cash = 0;
        int years = 0;
        double pv = 0;
        String line = null;

        String filename = "bank.txt";

        Scanner in = new Scanner(System.in);

        System.out.println("How much money would you like to have?");
        cash = in.nextDouble();

        System.out.println("How many years is your investment?");
        years = in.nextInt();

        Bank1 bank1 = new Bank1(cash, years);

        BufferedWriter bw = new BufferedWriter(new FileWriter(filename));       
        bw.write(String.valueOf(cash));
        bw.close();

        BufferedReader br = new BufferedReader(new FileReader(filename));       
        while((line = br.readLine()) != null)
        {
            //System.out.println(line);
        }

        System.out.println("The present value to invest over the years to reach goal: $"+bank1.presentValue());
        System.out.println("The furture value in the account will be: $"+bank1.futureValue());
    }
}

这是进行所有计算的第二个类。

public class Bank1 {

    private double cash;
    private double rate = .0425;
    private int years;

    public Bank1(double cash, int years){
        this.cash = cash;
        this.years = years;     
    }n

    public double presentValue(){
        double pv = cash/Math.pow((1+rate), years);
        double present = Math.round(pv *100);
        present = present/100;
        return present;
    }


    public double  futureValue(){
        double fv = this.presentValue()*Math.pow((1+rate), years);
        double future = Math.round(fv *100);
        future = future/100;
        return future;
    }

}

1 个答案:

答案 0 :(得分:1)

您最好的选择是阅读java文档中不同类型的Character / Byte流,每次我读/写数据时都会去那里找一个适合我需要的数据。

http://docs.oracle.com/javase/7/docs/api/java/io/package-summary.html

(这是您所说的import java.io.*代码中java.io包的文档,可让您访问文档中列出的任何内容。

当你说“我发现我想使用fileOutputStream但不知道如何合并到代码中”。你不必去除这个需要它的赋值,我会使用FileWriter或ObjectOutputStream。 ObjectOutputStream非常适合您尝试的操作。