开发者

need help on numberformat exception error

import java.lang.System;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SubMat {
    public static void main(String[] args) throws IOException {

        File file = new File("file1.txt");
        List<double[]> list = new ArrayList<double[]>();
       Scanner scanner = new Scanner(file).useDelimiter("\n");



        while (scanner.hasNext()) {     
            String[] values = scanner.next().trim().split(" "); 
             double[] floats = new double[values.length];
             for (int i = 0; i < values.length; i++) {
                 floats[i] = 开发者_如何学JAVADouble.parseDouble(values[i]);
                 }
                 list.add(floats);
                 } 
                 double[][] values = new double[list.size()][];
                 for (int i = 0; i < list.size(); i++) {
                     values[i] = list.get(i);
                     for (int j = 0; j < values[i].length; j++) {
                         System.out.printf(values[i][j]+"  ");

                         }
                         System.out.println();
                         }


                  int row =values.length;
                 int col=values[0].length;


    }}


May be you are getting this exception on this line

floats[i] = Double.parseDouble(values[i]);

Just print the values[i] may be it is null or contains any characters or special characters.


Quick fix: replace this line

floats[i] = Double.parseDouble(values[i]);

with

try {
   floats[i] = Double.parseDouble(values[i]);
} catch (NumberFormatException nfe) {
   System.out.println("String can't be parsed to a float value: " + values[i]);
   System.exit();  // brutal escape, because if you just continue, you'll have an
                   // illegal value (0.0) in your array
}

Note - if you want to ignore illegal inputs and continue, then you'll have to use a list instead of an array.


Addition - the question is possibly related to this on and there we see a sample input file. If this is the offending input, then may have a problem with the decimal point, which is a "dot" in that sample file and can be different in other locales.

How do you write decimal numbers on your system, 81.0 or maybe 81,0? If you use a different symbol for decimal separators, here's another quick fix (ugly as hell but easier then explaining the locale concepts...):

floats[i] = Double.parseDouble(values[i].replace('.', ',');
            // assuming you need a comma here to parse floats
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜