我正在尝试找到一种方法来增加使用 charAt 的值,但希望能够在 while 循环内更新它。以下是我当前的代码。我尝试在循环内重新创建变量并在末尾添加++ 以增加值,但收到意外的类型错误。
我试图让它采用您输入的值(即 3124)并将每个值连接起来,然后将它们加在一起。因此根据示例,它的值为 10。
public static void main(String[] args) {
int Num, counter, i;
String str1;
str1 = JOptionPane.showInputDialog("Enter any number: ");
Num = str1.length();
counter = 0;
i = Integer.parseInt(Character.toString(str1.charAt(0)));
NumTot = 0;
while (counter <= Num)
{
NumTot = i;
counter++;
i = Integer.parseInt(Character.toString(str1.charAt(0++)));
}
System.exit(0);
}
最佳答案
想法:
- 取一个整数
- 使用 mod 10 逐位提取数字
示例代码:
public class IntegerSum {
public static void main(String[] args) {
int i = 3124;
int sum = 0;
while (i > 0) {
sum += i % 10;
i /= 10;
}
System.out.println("Sum: " + sum);
}
}
输出:
Sum: 10
注意:我的答案是基于您的要求“我试图让它采用您输入的值(即 3124)并将每个值连接起来,然后将它们加在一起。因此根据示例,它的值为 10。”
关于java - 如何在 while 循环内增加 charAt 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610095/