编写一个程序,提示用户输入一个整数,然后输出数字的各个数字和数字的总和。例如,程序应输出3456的各个数字为3 4 5 6,总和为18,并输出-2345的各个数字为2 3 4 5,总和为14。
import java.util.*;
public class Integer {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input)) {
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++) {
String var = num.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
} else {
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++) {
String var = num.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
答案 0 :(得分:2)
我认为N
是用户输入的整数。在循环中执行此操作:
1)int d = N % 10;
- &gt;给你最后一位数字(现在根据需要处理)
2)N = N / 10;
- &gt;你摆脱了最后一个数字并为N
继续这样做,直到N变为0.