java - 如何在Java中读取数字的每个数字

标签 java while-loop

我正在尝试运行一个程序,该程序输出以整数形式输入的每个数字的总和。我将如何读取数字并输出每个数字?

示例:输入为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;
        }
    }
}


那就是我用来计算各个数字之和的代码,现在我只需要帮助输出各个数字。任何提示和技巧将不胜感激。

最佳答案

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.
        String numToString = "";

        while (num > 0) {
            int lastDigit = num % 10; 
            numToString +=lastDigit+" + ";
            sum = sum + lastDigit;
            num = num/10;
        }
        //eliminate the last + sign 
        numToString = numToString.substring(0,numToString.lastIndexOf("+")).trim();
        System.out.println(numToString +" = " +sum);
    }
}

关于java - 如何在Java中读取数字的每个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39859633/

相关文章:

java - 从另一个 JSON 数组中的 JSON 数组解码信息

java - 为字符串创建随机

java - 删除Weka实例的特定属性(列)

java - 我有一个do while循环问题。谁能告诉我为什么这不起作用?

javascript - JavaScript 99Bottles-无限循环

python - While循环不中断

c++ - 使用WHILE循环的直角三角形的C++代码

java - 将图像下载到内部存储并在 android 中读取

java - 如何排除Maven插件配置(无法识别的参数-encoding)

c - C中的Printf函数直到while循环完成才打印