Creating a small battleship game on Android that will use RMI and Tomcat.
I need to load data from a text file “boards.txt” and possibly store it in a HashMap in order to query it.
I cannot attach the file but below is a screenshot of the .txt file in Notepad. It displays the board layout for 10,000 Battleship game boards (I think it’s that number anyway) which are 10×10 grids.
So each 100 characters of the file will be the locations of the different ships and blank spaces for a 10 x 10 grid with each separated by a line break.
What I’m struggling with is the actual parsing. I think saving the data to a HashMap will make it easier to search through for picking a random board layout. Below is the code that I am currently using to read in the data.
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("C:\\Path\\boards.txt"));
HashMap<String, String> map = new HashMap<String, String>();
while (scanner.hasNextLine()) {
String columns = scanner.nextLine();
map.put(columns, columns);
}
System.out.println(map);
}
Now the main reason I have it like this was just to get rid of errors. Previously my code was like this:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("C:\\Path\\boards.txt"));
HashMap<String, String> map = new HashMap<String, String>();
while (scanner.hasNextLine()) {
String[] columns = scanner.nextLine().split(" ");
map.put(columns[0], columns[1]);
}
System.out.println(map);
}
But, I was getting an out of bounds exception. Due to the fact there is no blank spaces to split most likely.
OK so my main issue is, how do I either save the entire .txt file to a HashMap and only display one line of 100 characters at a time.
And Secondly (lower priority) – I would like to choose one line at random so I could create a random number between 1-10000 to display one line. I thought of using a String, Integer HashMap and somehow have a index value for each line but I’m not sure how I would do that.
**EDIT
Sorry I forgot to add the screenshot. Here it is:

Thank you for your answers, I’ll read through them now
To answer your questions directly:
1) You pretty much had your file reader, but you needn’t bother with the
Map, aListwill suffice.2) To grab a random line, just pick a random index into the
List.Now, all that said, if you don’t need to load the whole file, don’t. If you just need to grab a random line from the file then go right for it and save yourself computation and memory.
To do so, you’ll first need to known the number of lines in the file.
This question gives you:
Now you know how many lines there are and can pick one at random:
Then you can grab that line and ignore the rest: