问题描述
我的程序让用户输入一个5位数的数字,我需要一种方法来取5位整数并将所有数字加在一起。例如,用户输入26506,程序执行2 + 6 + 5 + 0 + 6并返回19.我相信这可以通过某种循环来完成但不确定从哪里开始。
my program has the user enter some 5 digit number, I need a way to take that 5 digit integer and add all the digits together. For example, the user enters 26506, the program does 2+6+5+0+6 and returns 19. I believe this would be done by some sort of loop but am unsure of where to start.
为了澄清,这个整数可以是任何东西,只需要是5位数。
For clarification, this integer could be anything, just has to be 5 digits.
推荐答案
从我的脑海中,您可以将其转换为字符串并遍历每个字符,并使用(charAt)累积值(位置) - '0')。我现在远离java编译器,但我想这应该可行。只需确保您只有数字数据。
From the top of my head, you can convert it to string and iterate over each char, accumulating the value with ( charAt( position ) - '0' ). I'm away from a java compiler right now, but I guess this should work. Just make sure you have numerical data only.
这篇关于Java Integer补充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!