I'm writing to 2 textfiles and I wanted a eaiser way to read the textfiles without all the words and number laying to close to eachother so I chose to write them with a tab to seperate them. But when I do this my class LineNumberReader
seems to think that the tab is a new line.
I have 2 classes. TextWriting
and compareTextFiles
When I run my TextWriting
class I can get an output that is like this:
(1) word1
(2) word2
(3) word3
So it is working as intended. (I used spaces for formatting purposes, but the file contains the tabs correctly)
And in my other class compareTextFiles
I compare 2 textfiles that I wrote from the first class. The important code is this.
String word,word2;
int i;
lnr = new LineNumberReader(new FileReader(file));
while (sc.hasNext() && sc2.hasNext()) {
word = sc.next();
word2 = sc2.next();
lnr.readLine();
if (word.equalsIgnoreCase(word2)) {
i = lnr.getLineNumber();
System.out.println("Line number: " + i + " and the word: [" + word + "]" + " and the word " + "[" + word2 + "]" + " is the same!");
}
else
System.out.println("[" + word + "]" + " and " + "[" + word2 + "]" + " is not the same");
}
The output I am recieving is:
Line number: 1 and the word: [(1)] and the word [(1)] is the same!
Line number: 2 and the word: [asd] and the word [asd] is the same!
Line number: 3 and the word: [(2)] and the word [(2)] is the same!
Line number: 3 and the word: [yeye] and the word [yeye] is the same!
Line number: 3 and the word: [(3)] and the word [(3)] is the same!
Line number: 3 and the word: [he] and the word [he] is the same!
Why does it get stuck on 3 so many times, and does tab create a new line of some sort?
Your code calls LineNumberReader.readLine
for every scanner token. Presuming a) each Scanner uses the default delimiter (in which case each line has 2 tokens) b) LineNumberReader.readLine
increments the value returned by LineNumberReader.getLineNumber
until the the file has been fully read - then for each token (rather than each line) it will increment until the 3 lines are read (and then stop incrementing), resulting in the output you get.
An alternative suggestion (there are many ways to skin this cat): consider using only the 2 Scanner's to read the files, reading the files using the Scanner.readLine
method. For each line, increment a variable representing the line number and then parse the lines as needed.
int lineCount = 0;
while ( sc.hasNextLine() && sc2.hasNextLine() ){
lineCount++;
String line1 = sc.nextLine();
String line2 = sc2.nextLine();
//parse the lines
String[] line1tabs = line1.split("\t");
//etc...
}