Use Set#size()
System.out.println(hashtags.size());
質問
I was looking at this code and I was wondering what's the best way to change the output to state the number of hashtags instead of what the hashtags are? Like if you input #one #two blue red #one #green four #jaja hg instead of getting a output of [#one, #two, #jaja, #green] you would get a output of [4]
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class HashTags {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a line of text");
String tweet = scanner.nextLine();
Set<String> hashtags = getHashtags(tweet);
System.out.println(hashtags.toString());
}
public static Set<String> getHashtags(String tweet) {
String[] words = tweet.split(" ");
Set<String> hashtags = new HashSet<String>();
for (String word : words) {
if (word.startsWith("#")) {
hashtags.add(word);
}
}
return hashtags;
}
}
解決
Use Set#size()
System.out.println(hashtags.size());