user3120540
user3120540

Reputation: 27

Retrieving certain variables from a text file

I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers? The format of the text file can be seen in the link underneath.

Text file

The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.

Here's the code that i've got so far.

public static double getAverageItems (String filename, int policyCount) throws IOException {

Scanner input = null;
int itemAmount = 0;

input = new Scanner(new File(filename));
while (input.hasNext()) {
     if (input.hasNextInt()) {
        itemAmount = itemAmount + input.nextInt();
     }
  }
return itemAmount;

}

Upvotes: 0

Views: 68

Answers (2)

public static double getAverageItems (String filename, int policyCount) throws IOException {

    Scanner input = null;
    int itemAmount = 0;

    input = new Scanner(new File(filename));
    while (input.hasNext()) {
         String []var = input.nextLine().split("\\s+");
         itemAmount += var[2];
    }
    return itemAmount;
}

Upvotes: 0

Javier
Javier

Reputation: 12398

Just add input.nextLine():

 if (input.hasNextInt()) {
    itemAmount = itemAmount + input.nextInt();
    input.nextLine();
 }

From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Another approach would be parsing each line and taking the third column.

BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
   String line = r.readLine();
   if (line==null) break;
   String cols[] line.split("\\s+");
   itemAmount += Integer.parseInt(cols[2]);
}
r.close();

Upvotes: 4

Related Questions