package nameyu;import java.util.Scanner;public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input=new Scanner(System.in); System.out.print("Enter a number 0 and 1000 :"); int number =input.nextInt(); int bit=number%10; number=number/10; int ten=number%10; number=number/10; int kil=number%10; System.out.println("The sum of the digits is "+(bit+ten+kil)); } } 这是一种没有循环的做法,比较死板,但是很容易理解,下面介绍一种好的方法 续上: package nameyu;import java.util.Scanner;public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input=new Scanner(System.in); System.out.print("Enter a number 0 and 1000 :"); int number =input.nextInt(); int sum=0; while(number/10!=0){ sum=sum+number%10; number=number/10; } sum=sum+number; System.out.println("The sum of the digtits is :"+sum); } }
|