如何找到用户输入数字字符串的所有奇数的总和? [英] How do I find the sum of all odd digits of user input numeric string?

查看:47
本文介绍了如何找到用户输入数字字符串的所有奇数的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到用户输入数字字符串的所有奇数位数的总和.例如,如果输入为12235,则总和为1 + 3 + 5 = 9.

I need to find the sum of all odd digits of user input numeric string. For example, if the input is 12235, the sum would be 1 + 3 + 5 = 9.

这是到目前为止我的代码:

This is what my code looks like so far:

 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 );
   }
}

总和总是打印一个大数字,但我不知道如何使它打印正确的数字.请帮忙.谢谢.

The sum always prints a large number, but I do not know how to make it print the correct number. Please help. Thanks.

推荐答案

您可以按字符逐个检查字符串,如果当前字符表示奇数,则可以将其加到运行总和中.最初,您只是发现介于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.

这篇关于如何找到用户输入数字字符串的所有奇数的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆