从文本文件中获取值并将它们放在数组中

时间:2015-09-21 11:12:30

标签: java arrays text-files

目前在我的程序中我使用的是硬编码值,但我希望它能让用户使用任何文本文件并获得相同的结果。

import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;

public class a1_12177903 
{
public static void main(String [] args) throws IOException
{
    if (args[0] == null)
    {
        System.out.println("File not found");
    }
    else
    {       
    File file = new File(args[0]);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line = "";

    while (br.ready())
    {
        line += br.readLine();
    }

    String[] work = line.split(","); 
    double[] doubleArr = new double[work.length]; 
    for (int i =0; i < doubleArr.length; i++)
    {
        doubleArr[i] = Double.parseDouble(work[i]);
    }


    double maxStartIndex=0;
    double maxEndIndex=0;
    double maxSum = 0;

    double total = 0;
    double maxStartIndexUntilNow = 0;

    for (int currentIndex = 0; currentIndex < doubleArr.length; currentIndex++)
    {

        double eachArrayItem = doubleArr[currentIndex];

        total += eachArrayItem;

        if(total > maxSum)
        {
            maxSum = total;
            maxStartIndex = maxStartIndexUntilNow; 
            maxEndIndex = currentIndex;
        }
        if (total < 0)
        {
            maxStartIndexUntilNow = currentIndex;
            total = 0;
        }
    }

    System.out.println("Max sum         : "+        maxSum);
    System.out.println("Max start index : "+ maxStartIndex);
    System.out.println("Max end index   : "   +maxEndIndex);


}
}
}

我已修复它,因此它从命令行获取文本文件的名称。如果有人有办法改善这一点,我会很乐意接受任何改进。

4 个答案:

答案 0 :(得分:2)

您可以使用Java8 Streams执行此操作,假设每个条目都有自己的行

double[] doubleArr =  Files.lines(pathToFile)
                           .mapToDouble(Double::valueOf)
                           .toArray();

如果您在生产系统上使用它(而不是作为练习),那么在Try with Resources块中创建Stream是值得的。这将确保您的输入文件正确关闭。

try(Stream<String> lines = Files.lines(path)){
   doubleArr =  stream.mapToDouble(Double::valueOf)
                      .toArray();
}

如果您有逗号分隔列表,则需要先拆分它们并使用flatMap。

  double[] doubleArr =  Files.lines(pathToFile)
                           .flatMap(line->Stream.of(line.split(","))
                           .mapToDouble(Double::valueOf)
                           .toArray();

答案 1 :(得分:1)

    public static void main(String[] args) throws IOException {
    String fileName = "";
    File inputFile = new File(fileName);
    BufferedReader br = new BufferedReader(new FileReader(inputFile));

    // if input is in single line
    StringTokenizer str = new StringTokenizer(br.readLine());
    double[] intArr = new double[str.countTokens()];
    for (int i = 0; i < str.countTokens(); i++) {
        intArr[i] = Double.parseDouble(str.nextToken());
    }

    // if multiple lines in input file for a single case
    String line = "";
    ArrayList<Double> arryList = new ArrayList<>();

    while ((line = br.readLine()) != null) {
        // delimiter of your choice
        for (String x : line.split(" ")) {
            arryList.add(Double.parseDouble(x));
        }
    }
    // convert arraylist to array or maybe process arrayList

}

答案 2 :(得分:0)

此链接可能有所帮助:How to use BufferedReader。然后你会得到一个包含数组的String

接下来,您有几种方法可以将字符串分析为数组。

  1. 使用JSONArray解析它。有关详细信息,请在Google中搜索JSON。
  2. 使用函数split()将字符串解析为数组。见下文。
  3. 方式2的代码:

    String line="10,20,50";//in fact you get this from file input.
    String[] raw=line.split(",");
    String[] arr=new String[raw.length];
    for(int i=0;i<raw.length;++i)arr[i]=raw[i];
    //now arr is what you want
    

答案 3 :(得分:0)

如果您使用的是JDK8,请使用流。请注意设计原则/模式。似乎可以在此处应用策略/模板设计模式。我知道,这里没有人会要求你专注于设计指南。还请注意命名约定。 &#34;文件&#34;因为班级名称不是一个好名字。

相关问题