需求:
編寫函數統計一篇英語文章中不同單詞的個數(去除重複的單詞)
1、把文章拆分成單詞保存到數組
2、去除數組中重複的單詞
3、返回單詞個數
知識點:
數組、字符串操作、set集合 、接收鍵盤輸入(Scanner)
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* 功能:統計一篇英語文章中不同單詞的個數(去除重複的單詞)
* 作者:摘星
*/
public class Text {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("請輸入");
String st=sc.nextLine();
String[] buffer=st.split(" ",-1);
int n1=buffer.length; // 未去重前的單詞個數
Set<String> set = new HashSet<String>(Arrays.asList(buffer));
//AddAll是傳入一個List,將此List中的所有元素加入到當前List中
// 也就是當前List會增加的元素個數爲傳入的List的大小
int n2=set.size(); // 去重後的單詞個數
System.out.println("去重前單詞個數:"+n1+"去重後單詞個數:"+n2);
}
}
在這裏插入代碼片
遇到的問題:
在接收鍵盤輸入時,next方法不能接收空格,即遇到空格就只接收空格前的數據,
解決方法:使用nextLine方法,或者採用io流的方式接收字符串