JAVA 从键盘输入一个四位整数,计算并输出各位数字之和。

从键盘输入一个四位整数,计算并输出各位数字之和。(用两个类实现,一个带主方法的public类,一个计算各数字和的类)

第1个回答  2012-11-20
import java.util.Scanner;
class CalculateSum {
public CalculateSum(int inputValue) {
String num = inputValue+"";
char[] a=num.toCharArray();
int sum = 0;
for(char ch:a)
sum+=ch-48;
System.out.println("The sum is " + sum);
}
}
public class test2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("输入一个四位数整数:");
int inputValue = scan.nextInt();
CalculateSum cs = new CalculateSum(inputValue);
}
}
第2个回答  2012-11-19
import java.util.Scanner;
class CalculateSum {
public CalculateSum(int inputValue) {
int thousands = inputValue / 1000;
int hundreds = (inputValue % 1000) / 100;
int tens = (inputValue % 100) / 10;
int ones = inputValue % 10;
int sum = thousands + hundreds + tens + ones;
System.out.println("The sum is " + sum);
}
}
public class TestSum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("输入一个四位数整数:");
int inputValue = scan.nextInt();
CalculateSum cs = new CalculateSum(inputValue);
}
}本回答被网友采纳
相似回答