java 我需要分隔一个整数然后在java中将数字相加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10757470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I need to separate a integer then add the digits together in java
提问by Impact Pixel
Good morning, I am on now to lesson 4 and am having a bit of trouble using loops. Please note that I have seen it resolved using strings but I am trying to grasp loops.
早上好,我现在正在学习第 4 课,但在使用循环时遇到了一些麻烦。请注意,我已经看到它使用字符串解决,但我正在尝试掌握循环。
The reason for the trouble is I need to show both answers: The integer broken into individual number ex: 567 = 5 6 7
麻烦的原因是我需要显示两个答案:整数分解为单个数字例如:567 = 5 6 7
And then 567 = 18
然后 567 = 18
I am able to get the integer added together but am not sure on how to separate the integer first and then add the individual numbers together. I am thinking that I need to divide down to get to 0. For instance if its a 5 digit number /10000, /1000, /100, /10, /1
我能够将整数相加,但不确定如何先将整数分开,然后将各个数字相加。我想我需要除以得到 0。例如,如果它是一个 5 位数字 /10000、/1000、/100、/10、/1
But what if the user wants to do a 6 or 7 or even a 8 digit number?
但是如果用户想要输入 6 位或 7 位甚至 8 位数字呢?
Also I am assuming this would have to be first and then the addition of the individual integers would take place?
另外我假设这必须是第一次,然后会发生单个整数的相加?
thanks for the guidance:
感谢指导:
import java.util.Scanner;
public class spacing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
System.out.print("Enter a your number: ");
n = in.nextInt();
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Sum: " + sum);
}
}
回答by Vivin Paliath
Since this is a lesson, I won't give you the solution outright, but I will give you some hints:
由于这是一个教训,我不会直接给你解决方案,但我会给你一些提示:
- You're only thinking in
int
. Think inString
instead. :) This will also take care of the case where users provide you numbers with a large number of digits. - You willneed to validate your input though; what if someone enters "12abc3"?
String.charAt(int)
will be helpful.Integer.parseInt(String)
will also be helpful.
- 你只是在想
int
。String
而是考虑一下。:) 这也将处理用户为您提供大量数字的情况。 - 您将需要验证您的输入,虽然; 如果有人输入“12abc3”怎么办?
String.charAt(int)
会有所帮助。Integer.parseInt(String)
也会有帮助。
You could also look at using long
instead of int
; long
has an upper limit of 9,223,372,036,854,775,807 though.
你也可以看看 usinglong
而不是int
; long
但上限为 9,223,372,036,854,775,807。
回答by Lajos Arpad
//I assume that the input is a string which contains only digits
public static int parseString(String input)
{
char[] charArray = input.toCharArray();
int sum = 0;
for (int index = 0; index < input.length; index++)
{
sum += Integer.parseInt(charArray[index] + "");
}
return sum;
}
Use the function above, pass your input to the function and use the output as you like.
使用上面的函数,将输入传递给函数并根据需要使用输出。