Reputation: 73
I'm making my first 2d tile-based game. I made a "level.txt" file that looks something like this:
0 0 0 1 0 1 0 1 0 0 1 1 1 0
0 1 0 1 1 0 0 1 0 0 0 0 1 0
0 0 1 0 1 1 1 0 0 0 1 1 1 1
//and so on.
This basicaly determines what picture from a sprite sheet each tile uses (e.g 0 is grass, 1 is water). The level file currently must be a set size, but I want it to automaticaly determine how wide the level is (from how many numbers in a single line there is), and draw the grid accordingly, for easy customizing. Is there anyway to read the amount of numbers in a single line of the file? For example, if i have this:
0 1 0 1 1 0
How would i make a method return "6"? I have googled this problem, but i can't seem to find a answer.
If someone could post a simple example, I should be able to figure it out, and put it in my game. Thanks.
Upvotes: 1
Views: 57
Reputation: 26978
Or without the use of Tokenizer:
File f = new File("file.txt");
Scanner s = new Scanner(f);
String line = s.nextLine();
String[] numbers = line.split(" ");
int num_numbers = numbers.length;
Upvotes: 2
Reputation: 16987
Pretty simple:
public int countNumbers(String line) {
return new StringTokenizer(line).countTokens();
}
A StringTokenizer
is a class used to break up a string into "tokens". This returns the number of tokens.
Upvotes: 3