用java语言编写:计算并输出一个整数各位数字之和

2024年11月17日 04:29
有5个网友回答
网友(1):

草草的写了一个,你先看下,我要断网了,下次再聊
public class TestIncreace {

void TestInc(int n){
int []a = new int []{0,0,0,0,0,0,0,0};//这里可以测试8位数
int sum = 0;
for(int i = 0;i < a.length;i ++){
a[i] = n % 10;
n = n / 10;
sum += a[i];
}
System.out.println(sum);
}

public static void main(String[] args) {
TestIncreace t = new TestIncreace();
t.TestInc(1223);//括号内为要测试的数据

}
}

--------------------------------------------------------------------------------------
代码修改:

/*
* 输入一个整数n,输出n的各个位数之和,抛出异常
*/

import java.util.Scanner;

public class TestIncreace {

void TestInc(int n) throws Exception{

int []a = new int [n];
int sum = 0;
for(int i = 0;i < a.length;i ++){
a[i] = n % 10;
n = n / 10;
sum += a[i];
}
System.out.println(sum);

}

public static void main(String[] args) throws Exception {
try{
TestIncreace t = new TestIncreace();
System.out.println("请输入您要测试的数据:");
Scanner input = new Scanner(System.in);
int in = input.nextInt();
t.TestInc(in);//括号内为要测试的数据

}catch(Exception e){
System.out.println("非法数字");
}
}

}

网友(2):

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);
}


}

网友(3):

public int sum(int number) {
int result = 0;
String numStr = String.valueOf(number);
for(int i = 0; i < numStr.length(); i++) {
result += Integer.parseInt("" + numStr.charAt(i));
}
return result;
}

网友(4):

public int getSum(int a){
if(a<0){
a=-a;
}
if(a%10==a){
return a;
}else {
return a%10+getSum(a/10);
}
}

网友(5):

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