2

Currently I'm trying to read through some basic cells, in this format:

+-------+-------+
|       |       |
+-------+-------+

Now I need to get the string representation of the cell's contents and send it off to another method. The problem is that the cells have no pre-defined length. I'm reading these from a file, so my easiest option should be to just use the Scanner I already have set up. Problem is, I don't really know how for this case.

I have a strong feeling that I need to use the pattern somehow, but I'm at a complete loss on how to do it.

I could also probably just build it up somehow, but that strikes me as being painfully slow.

0

1 Answer 1

1

See javadoc for Scanner, it has an example :

String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

prints the following output:

 1
 2
 red
 blue 

Well you can use | as delimiter.

EDIT : To use | as a delimiter you should escape it, Use \\s*\\|\\s* or \\s*[|]\\s*. If you use | as it is, then you will get only 1st value 1 and exception InputMismatchException.

See below program and output :

public class Test {
    public static void main(String[] args) {
        String input = "1 | 2 | red | blue |";
        Scanner s = new Scanner(input).useDelimiter("\\s*\\|\\s*"); // or use "\\s*[|]\\s*"
        System.out.println(s.nextInt());
        System.out.println(s.nextInt());
        System.out.println(s.next());
        System.out.println(s.next());
        s.close();
    }
}

Output :

1
2
red
blue
Sign up to request clarification or add additional context in comments.

1 Comment

It seems to be treating the | as a logical operator, not a character. Calling it like this: "\\s|\\s" only grabs the first item from the cell, and it gives me an Invalid Escape Sequence error when I try to use a \ to quote it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.