1

我可能会以错误的方式解决这个问题,但我的问题是,我将如何为 fxRates 填充数组?

CAD,EUR,GBP,USD
1.0,0.624514066,0.588714763,0.810307
1.601244959,1.0,0.942676548,1.2975
1.698615463,1.060809248,1.0,1.3764
1.234100162,0.772200772,.726532984,1.0

这是我在 CSV 文件中的信息,我正在考虑使用扫描仪类来读取它。就像是

private double[][] fxRates;
String delimiter = ","
Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        fxRates = line.split(delimiter)
4

5 回答 5

1

您解决此问题的方法似乎还可以。但line.split(",")会返回一个一维字符串数组。您不能将其分配给fxRates. 而且您还应该知道行数或行数以便fxRates在开始时进行初始化。否则,您应该使用动态列表结构,例如ArrayList.

假设您的文件中有 50 行,您可以使用以下内容:

private String[][] fxRates = String[50][];
String delimiter = ",";
Scanner sc = new Scanner(file);     
int index=0;

while (sc.hasNextLine()) 
{
    String line = sc.nextLine();
    fxRates[index++] = line.split(delimiter)
}

请注意,我已将其声明fxRates为 2D 字符串数组,如果您需要双精度值,您应该就地或稍后进行一些转换。

于 2012-10-19T05:22:17.217 回答
1
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;

public class CSVReader{

    private String readFile(String path, Charset encoding) throws IOException
    {
        //Read in all bytes from a file at the specified path into a byte array
        //This method will fail if there is no file to read at the specified path
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        //Convert the array of bytes into a string.
        return new String(encoded, encoding);
    }

    public String readFile(String path)
    {
        try {
            //Read the contents of the file at the specified path into one long String
            String content = readFile(path, Charset.defaultCharset());

            //Display the string.  Feel free to comment this line out.
            System.out.println("File contents:\n"+content+"\n\n");

            //Return the string to caller
            return content;

        }catch (IOException e){
            //This code will only execute if we could not open a file

            //Display the error message
            System.out.println("Cannot read file "+path);
            System.out.println("Make sure the file exists and the path is correct");

            //Exit the program
            System.exit(1);
        }`enter code here`
        return null;
    }
}
于 2016-05-31T01:37:13.317 回答
0

我不建议您以这种方式解析 CSV,因为Scanner这太低级和原始的解决方案。相比之下,DOM/SAX 解析器更适合解析 XML,而不是正则表达式解析或任何不考虑文档结构的东西。有一些 CSV 解析器具有良好的 API,并在读取器初始化期间建议配置选项。看看易于使用的CsvReader。这是使用它的代码示例:

package q12967756;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;

import static java.lang.Double.parseDouble;
import static java.lang.System.out;

import com.csvreader.CsvReader;

public final class Main {

    private Main() {
    }

    private static final String MOCK =
            "CAD,EUR,GBP,USD\n" +
            "1.0,0.624514066,0.588714763,0.810307\n" +
            "1.601244959,1.0,0.942676548,1.2975\n" +
            "1.698615463,1.060809248,1.0,1.3764\n" +
            "1.234100162,0.772200772,.726532984,1.0\n";

    private static final char SEPARATOR = ',';

    public static void main(String[] args) throws IOException {
        // final FileReader contentReader = new FileReader("yourfile.csv");
        final StringReader contentReader = new StringReader(MOCK);
        final CsvReader csv = new CsvReader(contentReader, SEPARATOR);
        csv.readHeaders(); // to skip `CAD,EUR,GBP,USD`
        final Collection<double[]> temp = new ArrayList<double[]>();
        while ( csv.readRecord() ) {
            temp.add(parseRawValues(csv.getValues()));
        }
        final double[][] array2d = temp.toArray(new double[temp.size()][]);
        out.println(array2d[3][1]);
    }

    private static double[] parseRawValues(String[] rawValues) {
        final int length = rawValues.length;
        final double[] values = new double[length];
        for ( int i = 0; i < length; i++ ) {
            values[i] = parseDouble(rawValues[i]);
        }
        return values;
    }

}
于 2012-10-19T07:35:28.667 回答
0

另一个例子;

        Double[][] fxRates = new Double[4][];
        String delimiter = ",";
        //file code goes here
        Scanner sc = new Scanner(file);
        // Read File Line By Line
        int auxI = 0;
        // Read File Line By Line
        for (int auxI =0; sc.hasNextLine(); auxI++) {
            String line = sc.nextLine();
            System.out.println(line);
            String[] fxRatesAsString = line.split(delimiter);
            Double[] fxRatesAsDouble = new Double[fxRatesAsString.length];
            for (int i = 0; i < fxRatesAsString.length; i++) {
                fxRatesAsDouble[i] = Double.parseDouble(fxRatesAsString[i]);
                }
            fxRates[auxI] = fxRatesAsDouble;
        }
        //to double check it
        for (int y =0; y<fxRates.length; y++){              
            for (int x =0; x<fxRates.length; x++){
                System.out.print(fxRates[y][x] +" ");
            }
            System.out.println("");
        }
于 2012-10-19T05:57:35.633 回答
0

操作的结果split是一个String数组,而不是double. 所以缺少一步:将字符串转换为双精度:

private double[][] fxRates = new double[maxLines][4];
String delimiter = ","
int line = 0;
Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String[] fxRatesAsString = line.split(delimiter);
        for (int i = 0; i < fxRatesAsString.length; i++) {
            fxRates[line][i] = Double.parseDouble(fxRatesAsString[i]);
        }
于 2012-10-19T05:24:18.710 回答