English 中文(简体)
我需要将整数分开,然后在 java 中将数字相加
原标题:I need to separate a integer then add the digits together in java
  • 时间:2012-05-25 15:45:36
  •  标签:
  • java

早上好,我正在上第4课,在使用环时遇到一些麻烦。请注意,我已经看到它用字符串解决了,但我正在试图掌握环。

造成麻烦的原因是我需要向大家说明两个答案:整数破碎成个人编号,例如:567=5 6 7

然后567=18

我可以把整数加在一起,但不确定如何先将整数分开,然后将单个数字加在一起。我想我需要将整数除以到零。例如,如果它的5位数是1000,1000,/100,/10,/1,

但如果用户想要做一个6、7甚至8位数的数字呢?

我还假设这必须先进行,然后再增加个别整数?

感谢指导:

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);

        }
}
最佳回答
//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;
}

使用上面的函数,将输入传送到函数中,并随意使用输出。

问题回答

由于这是一个教训,我不会给你 彻底的解决方案, 但我会给你一些提示:

  1. You re only thinking in int. Think in String instead. :) This will also take care of the case where users provide you numbers with a large number of digits.
  2. You will need to validate your input though; what if someone enters "12abc3"?
  3. String.charAt(int) will be helpful.
  4. Integer.parseInt(String) will also be helpful.

您也可以使用 long 而不是 int ; long 的上限为9,223,372,036,856,854,775,807。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签