Sorry if my code seems bad, I'm not that experienced at programming. I need to transfer text from a .txt in the format of: Date-Name-Address-etc..
I'm reading in the file, then splitting the string with String.split("-"). I'm having trouble with the loops.
try{
File file = new File("testwrite.txt");
Scanner scan = new Scanner(file);
String[] test = scan.nextLine().split("-");
while(r<100){
while(c<6){
data[r][c] = test[c];
test = scan.nextLine().split("-");
c++;
}
r++;
c = 0 ;
}
System.out.println(data[1][5]);
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
It looks like you're calling scan.nextLine() too often. Every time you call scan.nextLine(), it advances the Scanner past the current line. Assuming your file has 100 lines, each with 6 "entries" (separated by "-"), I would move
test = scan.nextLine().split("-");
to the end of the while loop (but still inside the loop) so that it gets called once per line.Edit...
Proposed Solution: Given a file in the form,
a-b-c-x-y-z
a-b-c-x-y-z ... (100 times total)
Use this code:
Then use data[line][index] to access your data.
Two dimensional array is just "array of arrays", so you can directly use
split
result to store the data of one line.I split tab separated files using the following:
Again, in my instance I am splitting on tabs (\t) but you can just as easily split on - or any other character, aside from new line characters.
Per The Javadoc for readline()
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
.Once you have your lines split up how you need, just assigned them to your array as required.