编写Java应用程序,求任意一个三位数的数字之和

2024-11-27 21:08:44
推荐回答(5个)
回答(1):

package string.scannar;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
while (true) {
System.out.println("请输入你要计算的数字,以符号','分割:");
Scanner sc=new Scanner(System.in);
String num=sc.nextLine();
System.out.println("求的和为:"+getSum(num));
System.out.println("是否继续Y/N?");
String flag=sc.nextLine();
if("N".equalsIgnoreCase(flag)){
System.out.println("程序结束......");
break;
}
}
}
/**
* 求给定集合的算数和
* @param nums 所有要求和的整数集合
* @return sum 结果
*/
public static int getSum(String num){
String[] nums=num.split(",");
int sum=0;
for (int i = 0; i < nums.length; i++) {
try {
sum += Integer.parseInt(nums[i]);
} catch (NumberFormatException e) {
System.out.println(nums[i]+":不是一个正确的整数请检查输入");
}
}
return sum;
}
}

回答(2):

import java.util.Scanner;
public class Test {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(n <100 || n > 999){
System.out.println("对不起,您的输入有误,请重新输入一个三位数:");
n = sc.nextInt();
}
int a = n%10;//a是个位数;
int b = (n%100)/10;//b是十位数;
int c = n/100;//c是百位数;
int sum = a + b + c;
System.out.println("百位数是:"+c+"\t十位数是:"+b+"\t个位数是:"+a);
System.out.println("各位相加之和是:"+ sum);
}
}

回答(3):

package test;
public class Test {
public static void main(String args[]) {
System.out.println(getSum(123));
}

public static int getSum(int num) {
int a = num % 10;
int b = (num / 10) % 10;
int c = num / 100;
return a + b + c;
}
}

回答(4):

import java.util.Scanner;

public class count {
public static void main(String[] args) {
System.out.println("请输入您想要计算出各个位数之和的数字:");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
int sum = 0;

while (i > 0) {
sum = sum + i % 10;
i = i / 10;
}
System.out.println(sum);
}
}

不止局限于三位数哦 当然必须在int 的范围之内的数字 需要更大范围 可以自己更改啦

回答(5):

int a =123;
int sum=0;
while(a>0){
int b=a%10;
a=a/10;
sum+=b;
}