我需要找到用户输入数字字符串的所有奇数位的总和。例如,如果输入为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和用户输入的数字之间的奇数之和,这显然是不正确的。
userinput = JOptionPane.showInputDialog( "Enter a number. " , null);
for (int i = 0; i < userInput.length(); i++)
{
char c = userInput.charAt(i);
if ((c-'0') % 2 == 1)
{
sum += (c-'0');
}
}
System.out.println( sum );
替代对字符进行算术运算的一种替代方法是使用Character.digit(char, 10)
它更易于阅读,更安全并且更不易出错。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句