简体   繁体   English

使用扫描仪读取文件

[英]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. lineTokenizer不会从输入文件中读取*以外的字符,不是字符会存储在迷宫数组中。 Can you tell me where I'm going wrong? 你能告诉我我要去哪里了吗? Thanks! 谢谢!

You could also use FileInputStreams to read the file with a BufferedReader . 您还可以使用FileInputStreams通过BufferedReader读取文件。

I personnally use the Scanner only for console input. 我本人仅将Scanner用于控制台输入。

I think you should be using loops instead of just if. 我认为您应该使用循环而不是仅仅使用循环。

Try changing the 3rd line to: 尝试将第三行更改为:

while (lineTokenizer.hasNext())

Since you are using an if condition, the pointer is not moving ahead. 由于您使用的是if条件,因此指针不会向前移动。 You should use a loop to continuously read data from scanner. 您应该使用循环从扫描仪连续读取数据。 Hope that helps. 希望能有所帮助。

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. 我不知道您如何处理迷宫的初始化,但要避免任何ArrayIndexOutOfBounds,我会改用List中的List。 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***, *]] 上面的代码将为您提供以下列表: [[****, AAAAA*, *, ****], [*******, AAAAAA***, *]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM