[英]Using Scanner to read entire line of String in Java
我有以下代码:
Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.useDelimiter(System.getProperty("line.separator"));
for(int i=0; i<t ;++i) {
if(sc.hasNext()) {
String element = sc.next();
uniquePairs.add(element);
System.out.println(uniquePairs.size());
}
}
输入:
5
john tom
john mary
john tom
mary anna
mary anna
我的输出(标准输出)
1
2
3
3
4
预期产量
1
2
2
3
3
为什么不同? 是否由于Scanner$nextLine();
?
但是,如果执行以下更改,则会得到正确的输出:
删除行:
sc.useDelimiter(System.getProperty("line.separator"));
替换行:
String element = sc.next();
与:
String element = sc.next() + " " + scan.next()j
请说明相同吗?
这是给您错误输出的代码:
Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.useDelimiter(System.getProperty("line.separator"));
for(int i=0; i<t ;++i) {
if(sc.hasNextLine()) {
String element = sc.nextLine();
uniquePairs.add(element);
System.out.println(uniquePairs.size());
}
输出:
1个
2
3
3
4
问题是一旦您读取了int
值, new line character
就会被留下并在循环中被读取并产生错误的结果。 您可以使用nextLine()
读取该new line character
然后忽略它。 然后根据需要使用nextLine()
方法。
这是产生正确结果的代码。
Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine(); // Ignore the next line char.
for(int i=0; i<t ;++i) {
if(sc.hasNextLine()) {
String element = sc.nextLine();
uniquePairs.add(element);
System.out.println(uniquePairs.size());
}
输出:
1个
2
2
3
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.