KaiquanMah's picture
Scanner reader = new Scanner(new File("fileName.txt")); list.add(reader.nextLine());
a931ec5 verified
raw
history blame
2.07 kB
The file players.txt contains the names of the players, one name on each line.
Write the method
ArrayList<String> readPlayers()
which reads the contents of the file and stores it in a list,
so that each name is one element in the list.
Finally, the list is returned.
Use the Scanner class to read the file.
You can see a sample tutorial in the code above - 16a.
An example of calling the method
(note that the test program will draw a new set of contents for the file at each run - so the output will vary):
public static void main(String[] args){
ArrayList<String> list = readPlayers();
System.out.println(list);
}
Example output:
[Ann, Ann, Adam, Keith, Ann, Jane, Thomas, Jack]
==============================================================================
import java.util.Random;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;*/
public class Test {
public static void main(String[] args){
final Random r = new Random();
ArrayList<String> list = new ArrayList<>();
Scanner reader = new Scanner(System.in);
System.out.println("Testing reading the file...");
ArrayList<String> players = readPlayers();
System.out.println("Players in list:");
for (String player : players) {
System.out.println(player);
}
}
//add
public static ArrayList<String> readPlayers() {
ArrayList<String> list = new ArrayList<>();
try {
// NEED TO DEFINE ANOTHER SCANNER INSIDE TO READ FROM THE FILE!!!
Scanner reader = new Scanner(new File("players.txt"));
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
}
catch (FileNotFoundException e) {
System.out.println("Error: players.txt file not found");
}
return list;
}
}
Testing reading the file...
Players in list:
Thomas
Jack
Keith
Vance
Pete
Ann
Annie
Tom