public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); while(in.hasNext()) { String n = in.next(); int sum = 0; for(int i=0;i<n.length();i++) { sum += (int)n.charAt(i) - 48; } System.out.println(sum); } } }
解题思路:charAt方法:
java.lang.String.charAt()方法 返回 指定索引 处的 char值。索引范围 是从0 到length() - 1。
对于数组的索引,序列的第一个 char值 是在索引 为0,索引1,以此类推。。
这是String类中的关于这个方法的源代码:
---------------------
public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }
注意事项: charAt()方法的使用 sum += (int)n.charAt(i) - 48; 表示将输入的字符按ASCII码转换为整数,然后减掉48。
0.0分
2 人评分
2003年秋浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:746 |
2003年秋浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:581 |
文科生的悲哀 (C语言代码)浏览:1398 |
C二级辅导-计负均正 (C语言代码)浏览:480 |
川哥的吩咐 (C语言代码)浏览:609 |
简单的a+b (C语言代码)浏览:818 |
C语言程序设计教程(第三版)课后习题6.4 (C语言代码)浏览:376 |
C语言程序设计教程(第三版)课后习题8.4 (C++代码)浏览:444 |
龟兔赛跑预测 (C++代码)浏览:1180 |
C语言训练-求素数问题 (C语言代码)浏览:611 |