Hashset将空字符串作为java中的元素

时间:2016-10-16 06:45:17

标签: java hashset

我正在尝试向hashset添加元素,但它会在其中添加一个空元素。

最初我试过,

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]

所以问题必须是别的。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

第二种方法几乎是正确的 只需将sc.next()替换为sc.nextLine()