我想運行一個程序,輸出整數中輸入的每個數字的總和。我將如何閱讀數字並輸出每個數字?如何讀取Java中每個數字的每個數字
示例:輸入爲4053,輸出爲「4 + 0 + 5 + 3 = 12」。
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
while (num > 0) {
int lastDigit = num % 10;
sum = sum + lastDigit;
num = num/10;
}
}
}
這是我用來計算個人數字總和的代碼,現在我只需要幫助輸出個人數字。任何提示和技巧將不勝感激。
你這是什麼意思outputing? –
掃描儀必須逐個讀取每個數字以創建數字,然後分解爲每個數字。爲什麼不一次只讀一個角色? –
當您遍歷數字時,只需輸出每個'lastDigit'的值即可。 – nhouser9