【问题标题】:reading nodes from a file to make a graph -using java从文件中读取节点以制作图形 - 使用 java
【发布时间】:2014-10-26 20:14:28
【问题描述】:

错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "7 1"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at javaapplication3.JavaApplication3.main(JavaApplication3.java:19)

我正在尝试按如下方式读取文件内容,就像出现逗号一样,表示图中有一个直接箭头!从 3 到 7 有一个直接箭头,从 1 到 4 等等。

file.txt 内容:

3,7  1,4 7,8  0,5  5,2  3,0 2,9  0,6   4,9  2,6  6,4  1,5 8,2  9,0  8,3 4,5  2,3  1,6  3,5  7,6  

java代码:

导入 java.io.File; 导入 java.util.Scanner;

公共类 JavaApplication3 {

public static void main(String[] args) throws Exception 
{
    @SuppressWarnings("resource")
    Scanner inFile = new Scanner(new File("file.txt"));

    // Read the number of vertices
    String line = inFile.nextLine();
    String[] data=line.split("\\,");
        int part1=Integer.parseInt(data[0]);
    int part2=Integer.parseInt(data[1]);
\*I expect the 2 lines above to work like that :part1=3, part2=7 .but what I noticed there is aproblem about the space character .*/
        while(inFile.hasNext())
    {
        line=inFile.nextLine();
        int index =0;
        int count=0;
        char edges = ',';
        while(index<line.length()) {

            if(line.charAt(index)==edges){
                count++;
            }
            index++;
        }

    }

}

.

如果可以的话请帮帮我。

【问题讨论】:

    标签: java file graph


    【解决方案1】:

    您只是在有逗号的地方拆分line,并且您还想在有空格的地方拆分它。否则data 将如下所示:

    {"3", "7 1", "4 7", "8 0", ..., "5 7", "6"}
    

    而且您不能将"7 1"(或任何包含空格的其他)解析为int。

    要修复它,请将分隔符从 "\\," 更改为 ",|\\s+",如下所示:

    String[] data=line.split(",|\\s+");
    

    【讨论】:

    • 我建议使用正则表达式"[,\\s]",这样它就会在制表符等空格字符上拆分。
    • @codequestioneer 是,如果文件可能使用其他空白字符。我想它可能不会在这里,但我会编辑我的答案以防万一。看起来在某些地方连续有多个空格。感谢您的建议。
    • 我试过 "[,\\s]" 但也有问题,所以我尝试了第二个选项 String[] data=line.split(",|\\s+");现在可以了,可能是因为我使用了多个空格,就像你说的那样,谢谢@Lonenebula
    • @nana 我一开始在我的回答中使用了"[, ]",codequestioneer 建议使用 \s 而不是空格,我这样做了。但我也做了另一个修复,注意到文件连续包含多个空格。无论如何,如果有帮助,请考虑接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2015-11-07
    • 2020-10-28
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    相关资源
    最近更新 更多