P R
P R

Reputation: 1301

Using Scanner to read file

I am using Scanner to read the text file which contains *, spaces and alphabets. Two or more spaces can occur one after the other. Eg:

****  AAAAA* *    ****
    *******    AAAAAA*** *

I have written the following code:

lineTokenizer = new Scanner(s.nextLine());
int i=0;
if (lineTokenizer.hasNext()) {
    //lineTokenizer.useDelimiter("\\s");
    System.out.println(lineTokenizer.next());
    //maze[0][i]=lineTokenizer.next();
    i++;
}

The lineTokenizer doesn't read beyond the * from the input file not are the characters getting stored in the maze array. Can you tell me where I'm going wrong? Thanks!

Upvotes: 0

Views: 225

Answers (4)

geekgugi
geekgugi

Reputation: 389

Since you are using an if condition, the pointer is not moving ahead. You should use a loop to continuously read data from scanner. Hope that helps.

Upvotes: 1

faern
faern

Reputation: 73

I guess the code is changed many times while you tried different stuff. I don't know how you handle the initialization of maze but to avoid any ArrayIndexOutOfBounds I would use a List in a List instead. I made some guesses about what you wanted and propose this:

List<List<String>> maze = new ArrayList<>();        
Scanner s = new Scanner("****  AAAAA* *    ****\n    *******    AAAAAA*** *");
while (s.hasNextLine()) {
    List<String> line = new ArrayList<>();
    Scanner lineTokenizer = new Scanner(s.nextLine());
    lineTokenizer.useDelimiter("\\s+");
    while (lineTokenizer.hasNext()) {
        String data = lineTokenizer.next();
        System.out.println(data);
        line.add(data);
    }
    lineTokenizer.close();
    maze.add(line);
}
s.close();

I did not fully understand your goals. Does this do about what you want? The code above will give you the following list: [[****, AAAAA*, *, ****], [*******, AAAAAA***, *]]

Upvotes: 0

user1706698
user1706698

Reputation:

You could also use FileInputStreams to read the file with a BufferedReader.

I personnally use the Scanner only for console input.

Upvotes: 2

Lloyd Santos
Lloyd Santos

Reputation: 402

I think you should be using loops instead of just if.

Try changing the 3rd line to:

while (lineTokenizer.hasNext())

Upvotes: 1

Related Questions