编写程序,从键盘输入一个5位的整数,计算各位的数字之和,例如42965各位的数字之和是4+2+9+6+5=26
1个回答
展开全部
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Ad { public static void main(String[]args){ int a = 0; while(true) { System.out.println("请输入一个小于5位的整数:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { a = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(a >= 0 && a<= 99999) break; } if(a <= 9) System.out.println(a + "各位数字之和是:" + a); else if(a <= 99) { int i = 0,j = 0; i = a % 10; j = a /10; System.out.println(a + "各位数字之和是:" + (i + j)); } else if(a <= 999) { int i = 0,j = 0,k = 0; i = a % 10; j = a / 10 % 10; k = a / 100; System.out.println(a + "各位数字之和是:" + (i + j + k)); } else if(a <= 9999) { int i = 0,j = 0,k = 0,l = 0; i = a % 10; j = a / 10 % 10; k = a / 100 % 10; l = a / 1000; System.out.println(a + "各位数字之和是:" + (i + j + k + l)); } else if(a <= 99999) { int i = 0,j = 0,k = 0,l = 0,m = 0; i = a % 10; j = a / 10 % 10; k = a / 100 % 10; l = a / 1000 % 10; m = a / 10000; System.out.println(a + "各位数字之和是:" + (i + j + k + l + m)); } } }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询