2

The input file has this data:

1    // Comments 0 
0
14   // Comment  1 
4    // Comment  12 
32
21   // Comment  13

I need to just take those first integers, such as 1, 0, 14, etc. and put them into their own integer array. I have attempted to use Scanner, but using the regex split("\\s") does not seem to do what I need.

My idea is to bring it all into a String arraylist, which I have done, but at that point I can't figure out how to then strip out just those integers. A big part of the problem is that each comment also has integers in it, so if I just get out ALL of the integers on each line, those are also included...which I don't want.

If anyone could help walk me through the logic I need to process this file, I would appreciate it. Thanks.

Alfabravo
  • 7,493
  • 6
  • 46
  • 82
Brian Jay
  • 73
  • 11

6 Answers6

4

Using a Scanner is a good idea, but split isn't.

Assuming each relevant line starts with an Integer, contains no other relevant information and you want to stop once you encounter a line which doesn't respect this format, you could use the following code :

Scanner s = new Scanner(inputFile);
List<Integer> extractedIntegers = new ArrayList<>();
while (s.hasNextInt()) {    // check if the line starts with an integer
    extractedIntegers.add(s.nextInt()); 
    s.nextLine(); //consumes the rest of the line in order to skip over the comments
}
s.close();
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • Great solution. Turns out there is one added piece that I need to handle. Near the end of the file, a blank line is listed, and then a number ".1000", which I also need to capture. Assuming I use a String arrayList instead, how could I handle that? – Brian Jay Jan 30 '17 at 16:04
  • @BrianJay is the empty line important as a marker, or is it enough to search for a line that matches `^\.\d+$` ? – Aaron Jan 30 '17 at 16:27
  • No, the empty line is not important as a marker. Specifically, when I read in the ".1000", I need to put whatever integers follow into a different section of my integer array. So, the ".1000" is what is important. – Brian Jay Jan 30 '17 at 16:49
  • So your algorithm is actually "While I have not encountered the `.1000` line, store integers here ; then, store integers there" ? If so, I would use two while loops : the first test that a line does not start with/contain `.1000` with the `hasNext(Pattern p)` method while the second only checks that it hasn't reached the end of the file. The body of the loops would essentially remain the same as in my current answer. – Aaron Jan 30 '17 at 16:53
1

First you can read your file line line by line like this: How to read from files with Files.lines(...).forEach(...)?

Then for each line, you should use the regular expression parser library: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

The pattern to use is "^[0-9]+". ^ means the pattern starts at the beginning of the line, [0-9] means characters between 0 and 9 (all digits) and + means “at least once”. The rest of the line will be ignored.

Community
  • 1
  • 1
Tom
  • 834
  • 1
  • 14
  • 24
0

I think you can use this snippet below.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample2 {
    private static final String FILENAME = "file path";
    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                //TODO split the sCurrentLine with "//s"(space) if there is
                //a space after integer in each row and read first element from the array 
                //and validate the first element with integer regex('^\d+$') to validate 
                //if that is an integer or not

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
arun
  • 45
  • 1
  • 8
0

Here is a java 8 answer:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Class {
  private final static Pattern p = Pattern.compile("^([\\d.-]+)");

  public static void main(String... args) throws IOException {
    final Path path = Paths.get("/path/to/your/file.txt");
    Files.lines(path)
      .map(p::matcher)
      .filter(Matcher::matches)
      .map(m->m.group(1))
      .forEach(System.out::println);
  }
}
Andreas
  • 4,937
  • 2
  • 25
  • 35
0

A variant using Files and the Stream API and a regex pattern matcher.

final Pattern STARTS_WITH_NUMBER_PATTERN = Pattern.compile("^([\\d.]+)");
Files.lines(Paths.get(/* the path to your file */))
     .map(STARTS_WITH_NUMBER_PATTERN::matcher)
     .filter(Matcher::find)
     .map(Matcher::group)
     .collect(Collectors.toList());

Or omit the last line and just print the values out using forEach(System.out::println);.

If you just have an ArrayList<String> you can do basically the same. Just exchange the Files.lines...-line with: yourArrayList.stream().

Note that you can also do that with the Scanner. For the number parsing after some blank lines you might need to use some additional conditions. The stream solution at the other side might end up just a bit more readable.

Roland
  • 22,259
  • 4
  • 57
  • 84
0

import java.io.BufferedReader;

import java.io.IOException;

import java.io.FileReader;

public class ReadOnlufirstIntegerInFile {

private static void checkFirstInteger(String line) {

    char[] words = line.trim().toCharArray();
     for(int i = 0; i < words.length; i++) {

       if(words[i] >= 48 && words[i] <= 57) {
       System.out.println(words[i]);
       break;
    }
  }
}

public static void main(String[] args) {

    FileReader fileReader = null ;
    BufferedReader bufferedReader = null ;
    try {

        fileReader = new FileReader("F:\\VIKU\\a.txt");
        bufferedReader = new BufferedReader(fileReader);
        String line = bufferedReader.readLine();

        while( line != null ) {
        // System.out.println(line);
         checkFirstInteger(line);
         line = bufferedReader.readLine();
       }
    } catch (IOException e) {
        System.out.println(e);

    }

   finally() {
    try {
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    try {

        fileReader.close();
    } catch (Exception e2) {
        e2.printStackTrace();
    }
   }

}

}

VIKAS
  • 15
  • 4