Computer Science Canada How do I select lines from a file and output them? |
Author: | username123 [ Fri Nov 06, 2015 7:37 pm ] | ||
Post subject: | How do I select lines from a file and output them? | ||
What the title says. Here's what I have so far:
The files that are named after computer components are all identical to different 4-line sections of inventory.txt. I'm trying to replace the files with those sections. |
Author: | Insectoid [ Fri Nov 06, 2015 9:02 pm ] |
Post subject: | RE:How do I select lines from a file and output them? |
The easiest way is to just load the entire file into memory line-by-line, storing each line in the correct variable. Read the entire monitors section and store it all in monitors variables. Then read the entire motherboards section and save it all in motherboards variables. Java also permits random access to files, which is a bit more involved, but you can read up on it here. |
Author: | username123 [ Tue Nov 10, 2015 9:26 am ] | ||
Post subject: | Re: How do I select lines from a file and output them? | ||
I tried another method by storing the lines in an array and displaying each section using for loops. When I run it, each line is replaced by the word "null".
|
Author: | Insectoid [ Tue Nov 10, 2015 12:36 pm ] |
Post subject: | RE:How do I select lines from a file and output them? |
For some reason, nextLine() isn't properly returning the string. According to the specification, the method should never return null and will throw exceptions if it doesn't find a line, so it's more likely that that line is never actually reached. Maybe input2.hasNext() never actually returns true. |
Author: | username123 [ Tue Nov 10, 2015 5:02 pm ] |
Post subject: | Re: How do I select lines from a file and output them? |
I'm pretty sure it does though. If I add System.out.println(lines[i]) after lines[i] = input2.nextLine, it works. |
Author: | Insectoid [ Tue Nov 10, 2015 5:10 pm ] |
Post subject: | RE:How do I select lines from a file and output them? |
Okay, I've figured it out. Look at your for loop. On the first iteration, i = 0. Then you enter a while loop, which iterates over the entire file, repeatedly saving each line into lines[i]. i is still 0, so at the end of the while loop, lines[0] is given the last line in the file. lines[1] and up are all still unassigned, and therefore null. On the second iteration of the for loop, i=1. Then the while loop starts, and immediately exits, because you already got to the end of the file on the first iteration on the for loop. It does this 19 more times. When the for loop terminates, lines[0] contains the last line in the file, and lines[1] and up are still null. I hope I explained myself well enough. The fix should be obvious if I made any sense. |
Author: | username123 [ Tue Nov 10, 2015 5:42 pm ] |
Post subject: | RE:How do I select lines from a file and output them? |
I got rid of the while loop, and it works perfectly now. Thanks a lot! |