为什么 useDelimiter 的使用方式是这样的?

huangapple go评论69阅读模式
英文:

Why is the useDelimiter works like that?

问题

我一直在尝试读取一个包含类似如下内容的文本文件的文件夹:

K.Love,CLE,miss,2
K.Leonard,TOR,miss,2
K.Love,CLE,make,1
...

我进行了一些测试,但由于某种原因,当我使用`useDelimiter`来忽略或消除逗号时,我遇到了一个问题。首先我会展示代码:

import java.io.;
import java.util.
;

public class test {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("src\main\resources\games\game1.txt");
Scanner reader = new Scanner(inputFile);
reader.useDelimiter(",");
ArrayList names = new ArrayList<>();
while (reader.hasNext()) {
String input = reader.next();
names.add(input);
}
System.out.println(names.get(3));
reader.close();
}
}

当控制台在位置3打印出ArrayList时,我期望看到:

K.Leonard

但实际打印出来的是:

2
K.Leonard

当我将位置更改为数字4时,它会打印出:`TOR`(这是一个球队的名称)。
英文:

I have been trying to read a folder that contains any text files like this:

K.Love,CLE,miss,2
K.Leonard,TOR,miss,2
K.Love,CLE,make,1
...

I was doing some tests and for some reason when I use the useDelimeter to ignore or make the commas disappear, I encounter to a problem. I will show the code first:

import java.io.*;
import java.util.*;

public class test {
    public static void main(String[] args) throws FileNotFoundException {
        File inputFile = new File(&quot;src\\main\\resources\\games\\game1.txt&quot;);
        Scanner reader = new Scanner(inputFile);
        reader.useDelimiter(&quot;,&quot;);
        ArrayList&lt;String&gt; names = new ArrayList&lt;&gt;();
        while (reader.hasNext()) {
            String input = reader.next();
            names.add(input);
        }
        System.out.println(names.get(3));
        reader.close();
    }
}

What I expect when the console prints the arrayList at position 3 is:

K.Leonard

But instead of that it prints:

2
K.Leonard

When I change the position to number 4 it prints: TOR (Which is the name of a team).

答案1

得分: 2

你将分隔符定义为,,这意味着换行不再是分隔符。为了获得你期望的行为,你可以使用一个正则表达式,其中,或换行符都被视为分隔符:

reader.useDelimiter("[,\n]");
英文:

You defined your delimiter as ,, meaning that the newline is no longer the delimiter. To get the behavior you expect, you could use a regex where either a , or a newline character are considered as delimiters:

reader.useDelimiter(&quot;[,\n]&quot;);

huangapple
  • 本文由 发表于 2020年9月27日 05:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64082860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定