英文:
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
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("src\\main\\resources\\games\\game1.txt");
Scanner reader = new Scanner(inputFile);
reader.useDelimiter(",");
ArrayList<String> names = new ArrayList<>();
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("[,\n]");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论