-
Scanner Loop
I need to populate a tree list with the information from a text file. Which I'm able to do but some lines have more than one item in them (could be any number of items on the one line) so how do I get scanner to loop through them for only that line?
for example the file may look like:
Code:
Character
Profession
Pattern Pattern Pattern
Profession
Pattern Pattern
and the tree would be
Code:
Character
Profession
Pattern
Pattern
Pattern
Profession
Pattern
Pattern
what I have is this
Code:
while(input.hasNext()) {
characterName = input.nextLine();
character = new DefaultMutableTreeNode(characterName);
top.add(character);
prof = input.nextLine();
profession = new DefaultMutableTreeNode(prof);
character.add(profession);
while(theres another pattern on the line()) {
pat = input.next();
pattern = new DefaultMutableTreeNode(pat);
profession.add(pattern);
}
prof = input.nextLine();
profession = new DefaultMutableTreeNode(prof);
character.add(profession);
while(theres another pattern on the line()) {
pat = input.next();
pattern = new DefaultMutableTreeNode(pat);
profession.add(pattern);
}
}
-
You could use split to get more than one item from a line.
Code:
Scanner s = new Scanner(//your file);
while(s.hasNext()) {
String line = s.nextLine();
String[] items = line.split(" "); //omits whitespaces
for(int i = 0; i < items.length; i++)
add(items[i]); //your method for adding strings
}
Now, I'm not sure about this, I'd have to look at Scanners API, but i think you could also just use Scanners next() method, from a line "one two three" it should return one, then two, then three, but as I said, I'm not sure.
-
Thank so much for that I managed to get it working :D