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

3
  • That loop will run for every row element, creating a new array each time Commented Aug 8, 2013 at 9:55
  • You should use Scanner.nextLine() method to read each line. And then apply appropriate test on them. Commented Aug 8, 2013 at 9:58
  • Updated my answer. Found and tested a new regex. Good luck. Commented Aug 8, 2013 at 20:03

1 Answer 1

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)").

Sign up to request clarification or add additional context in comments.

4 Comments

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
No no no. You don't remove the slashes, you escape them. I've edited my answer; copy the new regex.
And yes, you are right. It's not next. It's trimmedLine, which is the line string without parantheses. Good observation.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.