public class Test {
public static void main(String[] args) {
int a = 1203;
int sum = 0;
while(a / 10 != 0){
sum += a % 10;
a = a / 10;
}sum = sum + a;
System.out.println("各位数字之和为" + sum);
}
}
testing
各位数字之和为6
import java.io.*;
public class ssss
{
public static void main(String[] args)
{
String num=null;
System.out.println("请输入一个整数,回车结束");
try
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
while((num=br.readLine())!=null&&num.length()!=0)
{
sum(num);
System.out.println("请输入一个整数,回车结束");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void sum(String num)
{
int b=0;
for(int i=0;i
b+=Integer.parseInt(num.substring(i,i+1));
}
System.out.println("该整数各个位上数字之和为:"+b);
}
}