我想创建一个将获取输入的所有数字之和的代码, 样本输入:241样本输出:7 但是在编写程序时有一些限制,只应使用基本操作,函数,而不必使用字符串函数来获取数字的所述总和(循环,/,%,*,-,+)允许使用。
我正在考虑的程序应该以此开头。
public class SumOfDigits{
public static void main(String args[]) throws Exception{
Scanner input = new Scanner(System.in);
int num = input.nextInt();
while(){
}
}
}
答案 0 :(得分:0)
一种选择是使用模数技巧来隔离然后求和输入数字中的每个数字:
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
点击下面的链接以获取有效的演示。
答案 1 :(得分:0)
该数字的模10将为您提供最后一位数字,由于整数除法,将其除以10将获得其他数字。您可以循环播放,直到处理完所有数字为止:
int sum = 0;
while (num != 0) {
sum += (num % 10);
num /= 10;
}
答案 2 :(得分:0)
您可以使用像这样的递归函数
import java.util.Scanner;
public class Main {
Scanner scanner ;
int result = 0;
public static void main(String[] args) {
// initialize new instance of current class
Main thisIns = new Main();
// initialize scanner instance for this instance
thisIns.scanner = new Scanner(System.in);
//calling for getting user inputs
int i = thisIns.getUserInput();
//get the sum of the integer
thisIns.getSumOfInterger(i, 0);
System.out.println("result is " + thisIns.result);
}
public int getUserInput(){
System.out.println("Please enter an integer : ");
int i = scanner.nextInt();
return i;
}
public void getSumOfInterger(int i, int moduler) {
if (i != 0) {
moduler += i%10;
getSumOfInterger(i/10, moduler);
// return 0;
}else{
result = moduler;
}
}
}