临时写的代码,你参考一下!- public class Test03 {
- public static void main(String[] args) {
- //定义字符串str接收要计算值的字符串
- String str = "123456789012";
- //去除字符串两端的空格
- String str1 = str.trim();
- //将字符串转换成字符数组
- char[] cs = str1.toCharArray();
- //定义两个int型变量sum1 sum2分别接收奇数为的和 偶数为的和
- int sum1 = 0;
- int sum2 = 0;
- //计算奇数为的和
- for (int i = 0; i < cs.length; i += 2) {
- sum1 = sum1 + Integer.parseInt(cs[i] + "");
- }
- //计算偶数为的和
- for (int i = 1; i < cs.length; i += 2) {
- sum2 += Integer.parseInt(cs[i] + "");
- }
- System.out.println("奇数项的和为:" + sum1);
- System.out.println("偶数项的和为:" + sum2);
- }
- }
复制代码 |