简体   繁体   中英

Exception in thread “main” java.lang.NumberFormatException: For input string: “0.353”

I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }
Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)

First three lines of my input file:

Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360

When I do System.out.println(Float.parseFloat("0.353")); , it prints out 0.353 as a float, so it must either be something wrong with your split or maybe there's a hidden character somewhere.

Could you try giving your entire code snippet in hopes of us being able to answer better?

Place this:

System.out.println("parts[2]=" + parts[2]);

between the two lines of code that you shared. I think you will find what you're looking for, which is the cause of your error.

Thanks for your anwsers. Eventually, it turns out that UTF-16 caused the problem. My input file was originally an excel file, then I saved it as UTF-16 txt, which caused this problem. I tried to save the input file as tab-delimited text file and it worked as expected.

This is a weird cause of the NumberFormatException. Hope it helps others come across the same problem.

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