0

I'm a java beginner and I have a small question about scanning from a text file Suppose I have a text file like this

abc
012
4g5
(0 0 0)
(0 1 3)
(1 2 6)
(1 1 0)
abcde
blahblah

Now I want to make an array for ONLY the string inside the parenthesis, meaning that how to tell the scanner to scan only the strings started from the first open parentheses, reset the array input after the following right parentheses, and eventually stop scanning after the last right parentheses. This is what I have so far:

*for the array, it will take the first digit as the row#, second digit as the col# and the third digit as the value

while (file.hasNext()) {
    if (file.next().equals("(")) {
        do {
            2Darray[Integer.parseInt(file.next())][Integer.parseInt(file.next())] = file.next(); 

        }
        while (!file.next().equals(")"));
}

thanks

Casper
  • 1,663
  • 7
  • 35
  • 62

1 Answers1

3

I recommend you used RegEx to match your parameters.

Have to mention that file in below case is a BufferedReader. Document yourself on that.

while ((line = file.readLine()) != null)
{
    if( line.matches("\\((.*?)\\)") ) // Match string between two parantheses  
    {
         String trimmedLine = line.subString(1, line.length - 1); // Takes the string without parantheses
         String[] result = trimmedLine.split(" "); // Split at white space   
    }
}

// result[0] is row#
// result[1] is col#
// result[2] is value

A flaw in this code is that you must respect the text line formatting as you mentioned in your question (e.g. "(3 5 6)").

Community
  • 1
  • 1
Georgian
  • 8,795
  • 8
  • 46
  • 87
  • Thanks for the help, however I get error at this "(?<=\()(.*?)(?=\))" invalid escape sequence, I removed the 2's \ \ the error is gone but nothing happened when i ran it. And for the next.split, isn't it line.split? cause there is no next.split – Casper Aug 08 '13 at 10:18
  • No no no. You don't remove the slashes, you escape them. I've edited my answer; copy the new regex. – Georgian Aug 08 '13 at 11:05
  • And yes, you are right. It's not `next`. It's `trimmedLine`, which is the line string without parantheses. Good observation. – Georgian Aug 08 '13 at 11:06
  • Yes it will. The RegEx finds the lines that correspond to `(x x x x...)`, and the `split(" ")` method takes a string and separates it at white space. Thus, it will work for any number of parameters. – Georgian Aug 13 '13 at 22:18