Reputation: 365
I'm new to Java. I'm trying to do a database on text file (Don't ask me why). The thing is I want to do is to read specific lines of a text file.
Text file:
Salary
3,400
21/12/2015
Tax Refund
3
22/12/2015
Tax Refund
320
23/12/2015
Savings Deposit
1,230
23/12/2015
Bonus
343
23/12/2015
Every 3 lines there is a new entry. For example Salary is the category, 3,400 is the amount and 21/12/2015 is a date. What i want to do is to read only the amounts (e.g. 3,400 3 320 1,230 etc.). The only thing I succeed to do is to print a the lines by matching them on true print statement, with this code:
while(opnEsoda.hasNext()) { // diabazei kathe seira sto txt
// diabazei kathe seira kai emfanizei to value tis kathe mias ana 3.
System.out.print("You got money from: " + opnEsoda.nextLine()+ ", ");
System.out.print("Amount: " + opnEsoda.nextLine()+", ");
System.out.print("Date: " + opnEsoda.nextLine()+". ");
System.out.println();
}
opnEsoda
is the Scanner and prints:
You got money from: Salary, Amount: 3,400, Date: 21/12/2015.
You got money from: Tax Refund, Amount: 3, Date: 22/12/2015.
You got money from: Tax Refund, Amount: 320, Date: 23/12/2015.
You got money from: Savings Deposit, Amount: 1,230, Date: 23/12/2015.
You got money from: Bonus, Amount: 343, Date: 23/12/2015.
Upvotes: 1
Views: 5146
Reputation: 3596
This in my opinion is a bit cleaner than just skipping lines and it allows you to have access to the skipped elements incase you need them later :)
do
{
String[] entry = new String[3];
for (int i = 0; i < 3; i++)
{
if (opnEsoda.hasNextLine())
{
// Trim removes leading or trailing whitespace.
entry[i] = opnEsoda.nextLine().trim();
}
}
System.out.println(entry[2]);
}
while (opnEsoda.hasNextLine)
Upvotes: 2
Reputation: 1716
You can use below JAVA8 code and get file in format of list of String. It will be easy to retrieve line number 'n' for list.
int n=2;
List<String> fileLines = Files.readAllLines(Paths.get("c:\\abc.txt"));
while(n<fileLines.size()){
fileLines.get(n);
n+=3;
}
Upvotes: 2
Reputation: 7376
Just skip the other lines :-)
while(opnEsoda.hasNext()) {
// skip category
opnEsoda.nextLine();
System.out.print("Amount: " + opnEsoda.nextLine()+", ");
// skip date
opnEsoda.nextLine();
System.out.println();
}
Upvotes: 3