public String printx() {
Scanner cc = new Scanner(System.in);
String tx = new String(cc.next().getBytes(), "utf-8"); // 編譯錯誤
return tx;
}
同 UnsupportedEncodingException。推薦使用 StandardCharsets.UTF_8 並在方法內部 try-catch 轉為非受檢異常,簡化調用者代碼。
public String printx() {
try (Scanner cc = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
return cc.nextLine(); // 直接按 UTF-8 讀取,無需手動轉碼
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
Scanner 構造器指定編碼讀取,返回的 String 內部已是 UTF-16,無需再轉碼。