我需要找到用户输入数字字符串中所有奇数位的总和。例如,如果输入为 12235,则总和将为 1 + 3 + 5 = 9。
到目前为止,这是我的代码的样子:
import javax.swing.JOptionPane;
public class sumOfAllOddDigits
{
public static void main( String[]args )
{
int a;
int sum = 0;
String userinput;
userinput = JOptionPane.showInputDialog( "Enter a number. " , null);
a = Integer.parseInt(userinput);
for (int i = 0; i <= a; i++)
{
if (i % 2 == 1)
{
sum += i;
}
}
System.out.println( sum );
}
}
总和总是打印出很大的数字,但我不知道如何让它打印出正确的数字。请帮忙。谢谢。
最佳答案
现在您正在计算 0 和您输入的数字之间的所有奇数的总和。
相反,您需要从输入的数字中获取每个单独的数字。可以在这里找到解决方案 -- How to get the separate digits of an int number?
然后,对于每个数字,如果该数字是奇数,则将其添加到运行总和中。
关于java - 如何找到用户输入数字字符串的所有奇数位的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246480/