package com.loaderman.test; import java.util.HashSet; import java.util.Scanner; public class Test2 { /** * * 使用Scanner從鍵盤讀取一行輸入,去掉其中重復字符, 打印出不同的那些字符 * aaaabbbcccddd * * 分析: * 1,創建Scanner對象 * 2,創建HashSet對象,將字符存儲,去掉重復 * 3,將字符串轉換為字符數組,獲取每一個字符存儲在HashSet集合中,自動去除重復 * 4,遍歷HashSet,打印每一個字符 */ public static void main(String[] args) { //1,創建Scanner對象 Scanner sc = new Scanner(System.in); System.out.println("請輸入一行字符串:"); //2,創建HashSet對象,將字符存儲,去掉重復 HashSet<Character> hs = new HashSet<>(); //3,將字符串轉換為字符數組,獲取每一個字符存儲在HashSet集合中,自動去除重復 String line = sc.nextLine(); char[] arr = line.toCharArray(); for (char c : arr) { //遍歷字符數組 hs.add(c); } //4,遍歷HashSet,打印每一個字符 for(Character ch : hs) { System.out.print(ch); } } }