可以使用String的charAt取得個別的輸入字元,將字元轉成String並包在Integer.parseInt函式裡面,將回傳的數值加總起來就可以得到答案了
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class test { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String num = br.readLine(); int sum = 0; try { for (int i = 0; i < num.length(); i++) { sum += Integer.parseInt((num.charAt(i) + "")); } } catch (NumberFormatException ex) { System.out.println("該值不是為數值"); return; } System.out.println(sum); } }