且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到用户输入数字字符串的所有奇数的总和?

更新时间:2023-02-10 07:46:57

您可以按字符逐个检查字符串,如果当前字符表示奇数,则可以将其加到运行总和中.最初,您只是发现介于0和用户输入的数字之间的奇数之和,这显然是不正确的.

You can just check the string character by character, and add to the running sum if the current character represents an odd digit. Initially you were just find the sum of odd numbers between 0 and the number input by the user, that would obviously be incorrect.

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),它更易于阅读,更安全且更不易出错.

An alternative to doing arithmetic on characters would be to use the Character.digit(char, 10) it's easier to read, safer, and less error prone.