-1

有没有办法逐行将文件读入Java,每行都有一系列整数(每行不同数量的整数)。例如:

2 5

1 3 4 5

2 4 8

2 3 5 7 8

等等

我会将每行中的行号和数字读入一个二维数组。

现在,这是我的代码:

int i=1, j;
try{
  Scanner sc=new Scanner(new File("mapinput.txt"));
  while(sc.hasNext()){
    String line=sc.nextLine();
    while(line!=null){
      j=sc.nextInt();
      Adj[i][j]=1;
    }
    i++;        
  }
} catch(Exception e){System.err.println(e);};

我看到,这段代码的问题在于它在 String 行之后读取整数;我希望它读取那一行中的数字。有没有办法从字符串中读取数字?

更新:
我决定使用 StringTokenizer 路线;但是,当它到达我文件的最后一行时,我收到 java.util.NoSuchElementException: No line found 错误。这是我更新的代码:

try{
  Scanner sc=new Scanner(new File("mapinput.txt"));
  String line=sc.nextLine();
  st=new StringTokenizer(line, " ");
  do{
    while(st.hasMoreTokens()){
      j=Integer.parseInt(st.nextToken());
      Adj[i][j]=1;
    }
    line=sc.nextLine();
    st=new StringTokenizer(line, " ");
    i++;        
  }while(st.hasMoreTokens());
} catch(Exception e){System.err.println(e);};
4

2 回答 2

0

一旦您阅读了一行,您就可以执行以下操作

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

并根据您的要求使用字符串数组

于 2014-05-08T00:55:10.917 回答
0

查看 Java 库中的 #StringTokenizer 类。

您可以轻松地遍历文件并拉出integers由空格分隔的内容。它可以很好地处理两个 + 位整数。

要直接回答您的问题,有一种方法可以从String.

调查

Integer.parseInt(String s);  

integer会从String.

文档在这里

String s1 = "15 ";
String s2 = "03";
int answer = Integer.parseInt(s1.trim()) + Integer.parseInt(s2.trim());
System.out.println(answer);

这打印出来:

18
于 2014-05-08T01:01:16.343 回答