Reputation: 19
I am writing a method that receives a file and returns an array list with every other word from the file. The files can contain multiple lines.
For example, if I scan through the File and it reads
{"red", "orange", "yellow", "green", "blue", "purple"}
The method should return the list
{"red","yellow","blue"}
I'm aware this is a rather simple question and if it has already been answered, please point me in the right direction. Also, I believe these are comma separated variables. So far I have my header and scanner declaration:
public static ArrayList<String>Skip(File file)
ArrayList<String> newList = new ArrayList<String>();
Scanner scanner = new scanner(file);
while(scanner.hasNextLine()){
*WHAT DO I DO HERE*
newList.add(____);
}
scanner.close;
}
return newList;
Upvotes: 1
Views: 151
Reputation: 12751
By default a Scanner uses whitespace as a delimiter, but you can explicitly set a different one. E.g.
scanner.useDelimiter(",");
To choose alternate lines, the easiest thing is to define a boolean
variable outside of the loop and then negate it (false -> true
and true -> false
) each time round the loop.
boolean includeItem = true;
while (...) {
...
includeItem = !includeItem;
}
SPOILER ALERT
Here's some code that puts it together and seems to do what you need:
public static List<String> alternateItemsFrom(File commaSeparatedFile)
throws FileNotFoundException {
List<String> results = new ArrayList<String>();
boolean includeItem = true;
try (Scanner scanner = new Scanner(commaSeparatedFile)) {
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String item = scanner.next().trim();
if (includeItem) {
results.add(item);
}
includeItem = !includeItem;
}
}
return results;
}
Also note:
When you create a Scanner
for a file, a FileNotFoundException
may be thrown. I needed to declare that exception on the method.
Although you can close a the scanner after the loop with scanner.close()
, there is a better way to do it in Java 7+ with a so-called try-with-resources block. This guarantees that the scanner will be closed even if an exception occurs while you're looping.
I've renamed the method and some of the variables to try to express their intentions more clearly.
Upvotes: 1
Reputation: 692073
The Scanner allows reading tokens, and tokens are, by default, separated by whitespace characters. But, as the javadoc indicates, you can use another delimiter.
Choose the appropriate delimiter for your file, then read the file token by token (and not line by line), and add each odd token to your List (you can use a boolean that goes from true to false and vice-versa at each iteration to know if the token must be kept or ignored).
Finally, a Scanner on a file must be closed, even if your code happens to throw an exception. So you should use try-with-resources to initialize your scanner, to make sure it's closed no matter what.
The javadoc is there to help. Read it carefully and try something.
Upvotes: 0