首页/ 题库 / [未知题]

读取一个在01000之间的整数,并将该整数的各位数字相加。例如:整数是932,各位数字之和为14

未知题
2021-07-17 17:55
查看答案

正确答案


读取一个在01000之间的整数,并将该整数的各位数字相加。例如:整数是932,各位数字之和为14


public class ExamDemo {


       public static void main(String[] args) {


              java.util.Scanner input = new java.util.Scanner(System.in);


              System.out.print("Enter an integer between 0 and 1000: ");


              int number = input.nextInt();


              int lastDigit = number % 10;


              int remainingNumber = number / 10;


              int secondLastDigit = remainingNumber % 10;


              remainingNumber = remainingNumber / 10;


              int thirdLastDigit = remainingNumber % 10;


              int sum = lastDigit + secondLastDigit + thirdLastDigit;


              System.out.println("The sum of all digits in " + number + " is " + sum);


       }


}



试题解析

标签: