我主要用C ++编程,我一直在努力将我的游戏移植到Java上。 我的一些代码遇到了一个小问题。 我的文本文件采用以下格式:
0:1 0:0 1:1 2:2 3:3
我用fscanf函数读取它,如下所示:
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中显示的格式化数据?显然没有fscanf lol afaik ......
答案 0 :(得分: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
答案 1 :(得分: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();
}
}
}