简体   繁体   中英

Take values from a text file and put them in a array

For now in my program i am using hard-coded values, but i want it so that the user can use any text file and get the same result.

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


}
}
}

I've fixed it so it takes in the name of the text file from the command line. if anyone has any ways to improve this, I'll happily accept any improvments.

You can do this with Java8 Streams, assuming each entry has it's own line

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

If you were using this on production systems (rather than as an exercise) it would be worth while to create the Stream inside a Try with Resources block. This will make sure your input file is closed properly.

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

If you have a comma separated list, you will need to split them first and use a flatMap.

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

}

This link may help: How to use BufferedReader . Then you will get a String containing the array.

Next you have several ways to analyze the string into an array.

  1. Use JSONArray to parse it. For further information, search google for JSON.
  2. Use the function split() to parse string to array. See below.

Code for way 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

Use streams if you are on JDK8. And please take care of design principles/patterns as well. It seems like a strategy/template design pattern can be applied here. I know, nobody here would ask you to focus on design guidelines.And also please take care of naming conventions. "File" as class name is not a good name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM