我试图向哈希集中添加元素,但它得到一个空元素。
最初我尝试过,
import java.util.*;
public class SetTrial{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
HashSet<String> names = new HashSet<String>();
for(int j=0; j<number;j++)
{
String text = sc.nextLine();
names.add(text);
}
System.out.println(names);
}
}
当我输入时,
5
a
b
c
d
e
它似乎只接受输入直到 d
并执行打印显示
[, a, b, c, d]
我的猜测是它在开始时接受换行符,所以我添加了 sc.next()
在代码中。
import java.util.*;
public class SetTrial{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
HashSet<String> names = new HashSet<String>();
sc.next();
for(int j=0; j<number;j++)
{
String text = sc.nextLine();
names.add(text);
}
System.out.println(names);
}
}
虽然这次看起来正确地接受了所有的输入,但结果是
[, b, c, d, e]
所以问题一定是别的原因。我该如何解决这个问题?
最佳答案
第二种方法几乎是正确的。
只需将 sc.next()
替换为 sc.nextLine()
。
关于java - 哈希集在java中获取空字符串作为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067641/