【问题标题】:Convert String value from a file to integer将字符串值从文件转换为整数
【发布时间】:2015-01-31 02:52:25
【问题描述】:

我正在从文件中读取整数值,我应该使用它来计算函数 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();
        }


    }

}

【问题讨论】:

  • 您在while 循环中读取了整个文件,因此实际上只使用了values 的最后一个值。 values 到底在哪里定义的?
  • @PM77-1 这是一个字段。在类声明的顶部定义。

标签: java bufferedreader parseint


【解决方案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 块中这样做。

【讨论】:

  • 谢谢,在我打印出想要的结果之前,我能够正确地计算出我想要的循环。但是,即使我在我的代码中使用过,我仍然在运行时遇到 NumberFormatException。它显然是由于字符串连接,但我该如何解决?您能否详细说明您的试用资源提示?
  • @FabienL。对于try-with-resources,我为您提供了文档链接和示例。至于String 连接,您发布的代码没有。
猜你喜欢
  • 2017-06-11
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 2012-03-26
  • 2021-12-14
  • 1970-01-01
相关资源
最近更新 更多