2013-08-02 95 views
2

我主要用C++編寫程序,我一直致力於通過Android將我的遊戲移植到Java。 我的一些代碼遇到了一個小問題。 我的文本文件的格式如下:用java讀取一個格式化的文本文件

for(int Y = 0;Y < MAP_HEIGHT;Y++) { 
    for(int X = 0;X < MAP_WIDTH;X++) { 
     Tile tempTile; 

     fscanf(FileHandle, "%d:%d ", &tempTile.TileID, &tempTile.TypeID); 

     TileList.push_back(tempTile); 
    } 

我將如何在Java中所示的格式化數據讀取:

0:1 0:0 1:1 2:2 3:3 

我與fscanf函數像這樣讀它?顯然是沒有的fscanf笑AFAIK ...

+1

您是否嘗試過'Scanner'類?檢查[這個SO帖子](http://stackoverflow.com/questions/1414444/how-do-iread-formatted-input-in-java)。 – kwishnu

+0

展望現在,謝謝。 –

+0

看看這個[專題] [1] 所以,你可以使用掃描儀類java.util中 [1]:http://stackoverflow.com/questions/16981232/what-is-the-scanf-等價的方法在java和如何使用它 – yahor

回答

1

使用下面的代碼格式化字符串中的Java代碼

import java.util.StringTokenizer; 

public class Test { 

    public static void main(String args[]) 
    { 

     String str="0:1 0:0 1:1 2:2 3:3"; 
     format(str); 
    } 

    public static void format(String str) 
    { 
     StringTokenizer tokens=new StringTokenizer(str, " "); // Use Space as a Token 
     while(tokens.hasMoreTokens()) 
     { 
      String token=tokens.nextToken(); 
      String[] splitWithColon=token.split(":"); 
      System.out.println(splitWithColon[0] +" "+splitWithColon[1]); 
     } 

    } 

} 

輸出:

0 1 
0 0 
1 1 
2 2 
3 3 
+0

不幸的是,不幫助我。原因是因爲我只對數值感興趣。 「:」也是一個分隔符。每個圖塊都需要這組值(1:0),不包括冒號。代表該瓷磚屬性的兩個數字。所以基本上每個「2:0」代表一個單獨的瓷磚。 –

+0

所以基本上你想輸出「1 0」? –

+0

種,基本上 瓷磚T =新瓷磚(); T.prop = 1; T.type = 0; –

0

也許你這樣的代碼:

package test; 

import java.util.Scanner; 
import java.util.regex.MatchResult; 

public class Test { 

    public static void main(String args[]) { 

     String str = "0:1 0:0 1:1 2:2 3:3"; 
     format(str); 
    } 

    public static void format(String str) { 

     Scanner s = new Scanner(str); 

     while (s.hasNext("(\\d):(\\d)")) { 
      MatchResult mr = s.match(); 
      System.out.println("a=" + mr.group(1) + ";b=" + mr.group(2)); 
      s.next(); 
     } 
    } 
} 
+0

你將如何在2維for循環中使用它? –