Infinite loop when reading text file
Hi, I'm new to Java and I'm currently doing a big project that is basically a library system.
Background...skip down to * for current problem...
Users can have a max of 3 books out of any time, and I'm creating a 2d array of size [3] [12] to store 12 parts of information for each of the books.
The last 3 parts of information are the books average rating (out of 5), what the user rated the book out of 5 and the number of times the book has been rated. I'm reading from a textfile UsersContributed.txt and Contributions.txt.
Contributions.txt has lines seperated by the deliminator # as follows:
thebooksISBN#reviews#average rating#numberoftimesrated#suggestedCover#
UsersContributed.txt has lines seperated by the deliminator # as follows:
studentNumber#ISBN#what rating the user gave the book#
I had a button that when clicked would fill the array, it worked fine for the first line in each of the above mentioned files but if additional lines were added to the textfile, it would not process them, so I decided to change my structure completly and first fill an array with all lines of the above textfiles and then work from there..
* This is my current code in a class that I call that I just want to use to fill an array with all the lines of the textfile UsersContributed.txt.
Code:
public String[] getUsersContributed() throws FileNotFoundException
{
int lines = 0;
int count = 0;
Scanner sc = new Scanner(new File("UsersContributed.txt"));
while (sc.hasNext())
{
lines++;
}
sc.close();
String lined[] = new String[lines];
System.out.println("Num of lines: " + lines);
Scanner ac = null;
try
{
ac = new Scanner(new File("UsersContributed.txt"));
} catch (FileNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
while (ac.hasNext())
{
lined[count] = ac.nextLine();
count++;
}
ac.close();
return lined;
}
When I call the method, my program freezes with no errors.
When I debug it, I see that the code:
Code:
while (sc.hasNext())
{
lines++;
}
never stops looping! I don't understand why, I have used the same looping structure with that textfile in other methods that work fine, eg:
Code:
while (ac.hasNext())
{
String lined = ac.nextLine();
lines[counter] = lined; //building up array of each line from textfile
counter++;
}
Please help me!