0

I need to read a text file that looks something like this

8 7 ~~~~~~~ ~~~~~~~ B~~~~~~ ~~~~~~~ ~~~~B~~ ~~~~B~~ ~~~~~~B ~~~~~~~ ~~~~~~~ 

My program is recreating a Battleship game. I need to accept the values 8 and 7 but only print from the second line down. I'm supposed to use string.split (i believe). I need to print only the lines with ~'s and B's. I have the code already for reading the file, I'm just unsure how to split the file by line breaks.

File file = new File(args[1]); try { Scanner sc = new Scanner(file); while (sc.hasNextLine()) { String themap = sc.nextLine(); System.out.println(themap); } sc.close(); } catch (Exception e) { System.out.println("ERROR: File does not exist"); } 

2 Answers 2

1

You already are reading it line by line using sc.nextLine(). It is going to read the file line by line. There's no need to use split to get each line. To prove that change your println statement to add something to each line you know is not in the file.

System.out.println( "Yaya " + themap ); 

If you see Yaya in front of each line when you run your program then you know you are reading it line by line, and themap points to one line out of the file at each pass of the loop.

After that then you just need to search within that line to find the B's and 8's and extract those into another data structure. There are lots of ways to do that, but check the String api for methods that can help with that.

Sign up to request clarification or add additional context in comments.

2 Comments

Right, that makes sense. So I don't need to split it, I just need to only print from the second line on. How do I access only those lines?
So without knowing a lot about what your data I'm having to guess a bit, but after second look your first line seems to contain some important information about your program. 8 7 seems to indicate how many rows and columns the board is large. You may need to keep that information. So the easiest way to do this is read the first line outside the loop then from then on your reading just the lines with the board. But you may need to parse out those two first numbers and keep them.
0

Use Java 8 Paths, Path, Files.readAllLines, and streams (the input is in /tmp/layout.txt):

package stackoverflow; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class StackOverflow { public static void main(String[] args) throws IOException { Path layout = Paths.get("/tmp", "layout.txt"); List<String> lines = Files.readAllLines(layout); lines.remove(0); // Don't print the first line. lines.stream().forEach(System.out::println); } } 

If you can't use Java 8, use

for (String line : lines) { System.out.println(line); } 

instead of

lines.stream().forEach(System.out::println); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.