将字符串值从文件转换为整数

时间:2015-01-31 02:52:26

标签: java bufferedreader parseint

我正在从文件中读取我应该用来计算函数multiple的整数值。

但是,在转换为整数后,似乎整数变量不会保留它们以供进一步计算。

请帮忙吗?

import java.io.*;

public class Functions {

    int values, mul7, mul11, mul13;

    public static void main (String []args) { 

        Functions go = new Functions ();
        go.multiple();
        // will call functions here
    }

    public void multiple () {


        int a = 7;
        int b = 11;
        int c = 13;

        try {
            File inputFile = new File ("JavaInputData.txt");
            FileReader fileReader = new FileReader (inputFile);

            BufferedReader reader = new BufferedReader (fileReader);

            String line = null;

            while ((line = reader.readLine()) !=null)
                    {   
                        values = Integer.parseInt(line);
                        System.out.println(values);
                    }

            mul7 = values % a;
            mul11 = values %b;
            mul13 = values %c;

            System.out.println(mul7);

            reader.close();
            }

        catch (Exception ex) 
        {
            ex.printStackTrace();
        }


    }

}

1 个答案:

答案 0 :(得分:1)

在循环体中执行计算和输出。像,

while ((line = reader.readLine()) != null)
{   
    values = Integer.parseInt(line);
    System.out.println(values);
    mul7 = values % a;
    mul11 = values % b;
    mul13 = values % c;
    System.out.printf("mul7 = %d, mul11 = %d, mul13 = %d%n", mul7, mul11, mul13);
}

此外,我建议您使用try-with-resources close() Reader;

try (File inputFile = new File ("JavaInputData.txt");
    FileReader fileReader = new FileReader (inputFile);
    BufferedReader reader = new BufferedReader (fileReader)) {

这样您就不必明确调用close()。但是,如果你打算明确地致电close();请在finally区块内完成。