【问题标题】:How to have the sum for the numbers in a string line? [closed]如何获得字符串行中数字的总和? [关闭]
【发布时间】:2020-11-07 19:52:58
【问题描述】:

在此任务中,我需要使用生成的字符串数据来遍历其上的所有字符,然后仅对字符串中的数字求和。 例子:如果我们有这个数据字符串

 5f395d07369071a505ef926527de2ac53e8c29e103dc63398315bc276224b81a

那么结果将是只取数字并将它们加在一起是2407

这是代码:

String studentId="22011151";
String studentName="Abed Alrahman Abuhilal";

int total=0;
String data =generateData(studentId);  //here is a method I didn't show

这里有逻辑错误

for(int i=0; i < data.length(); i++) {
    Boolean ok = Character.isDigit(data.charAt(i));
    total+=data.charAt(i);

System.out.println("StudentId:"+studentId+" my name is:"+studentName+" total is:"+total);

【问题讨论】:

  • 那么问题到底是什么?你有错误吗?结果错误?
  • 得到 2407 是错误的还是需要得到 2407 作为答案?

标签: java character charat


【解决方案1】:

我不确定您到底遇到了什么逻辑错误,但我有一些建议。据我所知,布尔值ok 是未使用的。即使您确实使用了它,您也需要在if 语句中添加total+=data.charAt(i); 行,以便仅将数字添加到总数中。像这样的:

      String data ="5f395d07369071a505ef926527de2ac53e8c29e103dc63398315bc276224b81a";
      int total = 0;
        
        for(int i=0; i < data.length(); i++) 
        {
            if (Character.isDigit(data.charAt(i)))
                total += data.charAt(i);
        }
        System.out.println(total);
    }
}

【讨论】:

    【解决方案2】:

    String.charAt 返回(在这种情况下)字符的 ASCII 表示('0' = 0x30,'1' = 0x31 等)。要获得数字,您应该使用以下内容更改循环中的行:

    total += data.charAt(i) - '0';


    UPD:通过应用此更改和 Geoff Zoref 的建议,您应该可以获得工作代码。

    【讨论】:

      【解决方案3】:

      data.charAt(i) 返回与字符相关的 ASCII 值。

      因此你得到了错误的答案。

      所以不要直接应用 char 值,请按照以下步骤操作。

      1. 获取char的字符串值

      2. 将字符串值解析为int

        for(int i=0; i < data.length(); i++) {
                Boolean ok = Character.isDigit(data.charAt(i));
                if (ok)
                    total += Integer.parseInt(String.valueOf(data.charAt(i)));
        

        }

      【讨论】:

        【解决方案4】:

        我认为问题在于您将 char 值添加到总数中。这与添加数字的值相同。例如,0 的 ASCII 值是 48,正如您在 wikipedia 条目的表中所见。您的问题的一种解决方案是这样写您的总和:

        total += Data.charAt(i) - '0';
        

        您可以这样做,因为您已经知道字符是一个数字,并且 ASCII 中的所有数字都按其值排序(0 是 48,1 是 49,等等)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-07-10
          • 2020-04-18
          • 2017-07-29
          • 1970-01-01
          • 2021-10-27
          • 1970-01-01
          • 2021-09-30
          相关资源
          最近更新 更多