Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

java - Java试图将意图读取为整数字符串(Java trying to read intention as an Integer string)

I'm trying to parse the a datafile.

(我正在尝试解析数据文件。)

This code has worked successfully for my other datfiles;

(该代码已成功地用于我的其他datfiles。)

however, I'm now getting an error.

(但是,我现在遇到一个错误。)

These datafiles are intended therefore the computer is trying to read the first space.

(这些数据文件旨在使计算机尝试读取第一个空格。)

How would I skip over this space?

(我将如何跳过这个空间?)

        String line = br.readLine();
            while (line != null) {

                String[] parts = line.split(" ");

                if (linecounter != 0)
                {
                    for (int j=0; j<parts.length; j++)
                    {

                        if (j==parts.length-1)
                            truepartition.add(Integer.parseInt(parts[j]));
                        else
                        {
                            tempvals.add(Double.parseDouble(parts[j]));
                            numbers.add(Double.parseDouble(parts[j]));
                        }

                    }

                    Points.add(tempvals);
                    tempvals = new ArrayList<Double>();
                }
                else
                {
                    //Initialize variables with values in the first line
                    // Reads each elements in the text file into the program 1 by 1
                    for (int i=0; i<parts.length; i++) {
                        if (i==0)
                            numofpoints = Integer.parseInt(parts[i]);
                        else if (i==1)
                            dim = Integer.parseInt(parts[i]) - 1;
                        else if (i==2)
                            numofclus = Integer.parseInt(parts[i]);
                    }
                }

                linecounter++;
                line = br.readLine();
            }
Data File
     75 3 4
     4    53 0
     5    63 0
    10    59 0

  ask by Anta translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This number format error is coming because you can't format space characters in the base 10. I can see many extra whitespaces is there in your input, split(" ") this will not work.

(数字格式错误即将到来,因为您无法在基数10中设置空格字符。我可以看到输入中还有很多额外的空格,split(“”)不能使用。)

So replace normal white space split with regex.

(因此,用正则表达式替换普通的空格分割。)

use the below code and it will take care of extra whitespaces in your input.

(使用下面的代码,它将处理输入中的多余空格。)

 String[] parts = line.trim().split("\s+");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...