2

I mainly program in C++ and I have been working on porting my game over to Java with Android. I ran into a short problem with some of my code. My text file is in this format:

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

I read it in with the fscanf function like so:

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);
    }

How would I read in the formatted data shown in Java? Obviously there is no fscanf lol afaik...

Yasin Khalil
  • 59
  • 1
  • 7
  • 1
    Have you tried the `Scanner` class? Check [this SO post](http://stackoverflow.com/questions/1414444/how-do-i-read-formatted-input-in-java). – kwishnu Aug 02 '13 at 02:43
  • Looking into that now, thanks. – Yasin Khalil Aug 02 '13 at 02:50
  • Look at this [topic][1] So you might use Scanner class from java.util [1]: http://stackoverflow.com/questions/16981232/what-is-the-scanf-equivalent-method-in-java-and-how-to-use-it – yahor Aug 02 '13 at 03:04

2 Answers2

1

Use the below code to format the string in 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]);
        }

    }

}

Output of Code :

0 1
0 0
1 1
2 2
3 3
Brijesh Thakur
  • 6,768
  • 4
  • 24
  • 29
0

Maybe your code like this:

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();
        }
    }
}
yuxiao
  • 1