gpt4 book ai didi

java - 如何在Java中读取数字的每一位数字

转载 作者:行者123 更新时间:2023-12-01 09:25:40 25 4
gpt4 key购买 nike

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

示例:输入为 4053,输出将为“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;
}
}
}

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

最佳答案

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 - 如何在Java中读取数字的每一位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39859633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com