如何在Java中读取数字的每个数字 [英] How to read each individual digit of a number in Java

查看:35
本文介绍了如何在Java中读取数字的每个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to run a program that outputs the sum of every digit of an entered in integer. How would I go about reading the number and outputting each digit?

示例:输入为 4053,输出为4+0+5+3 = 12".

Example: Input is 4053 the output would be "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;
        }
    }
}

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

That is the code I used for calculating the sum of the individual digits, now I just need help with outputting the individual digits. Any tips and tricks would be much appreciated.

推荐答案

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中读取数字的每个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆