简体   繁体   English

创建一个显示数字的数字总和的 Java 应用程序

[英]Create a java application that displays the sum of the digits of a number

I am relatively new to Java and I'm currently learning while, do while and for loops.我对 Java 比较陌生,目前正在学习 while、do while 和 for 循环。 I want to create an application that displays the sum of the digits of a number using these concepts but I have no idea how.我想使用这些概念创建一个显示数字总和的应用程序,但我不知道如何。 I previously created an application that displayed ONLY THE DIGITS of a number.我之前创建了一个只显示数字的应用程序。 Here it is.这里是。

int digit;
Scanner input = new Scanner(System.in);

do {
    System.out.println("Enter a positive integer: ");
    digit = input.nextInt();
} while (digit <= 0);
input.close();

String sdigit = digit + "";
for (int i = 0; i < sdigit.length(); i++){
    System.out.println(sdigit.charAt(i));
}

I'm trying to think of a possible way to expand on this program, but I have no idea why.我试图想出一种可能的方法来扩展这个程序,但我不知道为什么。 Once again, this program is not what I need, what I need is somehow to sum the digits of a number using for or while loops.再一次,这个程序不是我需要的,我需要的是使用 for 或 while 循环以某种方式对数字的数字求和。 Thank you!谢谢!

not much code has to be added for summing the digits :不需要添加太多代码来对数字求和:

First solution : using a substract with '0' character第一个解决方案:使用带有“0”字符的减法

int digit;
Scanner input = new Scanner(System.in);

do {
    System.out.println("Enter a positive integer: ");
    digit = input.nextInt();
} while (digit <= 0);
input.close();

String sdigit = digit + "";
int sum=0;       

for (int i = 0; i < sdigit.length(); i++){
    System.out.println(sdigit.charAt(i));
    sum = sum + (sdigit.charAt(i) - '0');
}

System.out.println("Sum is : "+sum);

Second solution : using Integer.parseInt which converts String to int :第二种解决方案:使用 Integer.parseInt 将 String 转换为 int :

int digit;
Scanner input = new Scanner(System.in);

do {
    System.out.println("Enter a positive integer: ");
    digit = input.nextInt();
} while (digit <= 0);
input.close();

String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
    System.out.println(sdigit.charAt(i));
    sum = sum + Integer.parseInt(sdigit.subString(i,i+1));
}

System.out.println("Sum is : "+sum);
int digit;
System.out.println("Enter a positive integer: ");
number= Integer.parseInt(System.console().readLine());

int sum=0;
int currDigit = 0;
while( number / 10 > 0) {
    currDigit  = number % 10; //fetching last digit
    System.out.println(currDigit);
    sum = sum + currDigit;
    number = number / 10;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM