-1

Here I in this task I need to use the generated string data to loop over all characters on it then sum only the numbers within the string. example: If we have this data string

 5f395d07369071a505ef926527de2ac53e8c29e103dc63398315bc276224b81a

Then the result will be when taking only the numbers and adding them together is 2407

this is the code :

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

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

I have a logic error here

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);
Bohemian
  • 412,405
  • 93
  • 575
  • 722

4 Answers4

1

String.charAt returns (in this case) an ASCII representation of a character ('0' = 0x30, '1' = 0x31 etc). To get a digit you should change your line in loop with the the following:

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


UPD: By applying this change and Geoff Zoref's suggestion you should get the working code.

nkrivenko
  • 1,231
  • 3
  • 14
  • 23
1

I am not sure exactly what logic error you are having, but I have a few suggestions. The Boolean ok is, as far as I can tell, unused. Even if you did use it, you would need to couch the line total+=data.charAt(i); in an if statement so that only the digits get added to total. Something like this:

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

data.charAt(i) returns ASCII value related to the character.

Hence you get the wrong answer.

So without applying the char value directly, follow the following steps.

  1. Get the string value of char

  2. Parse the string value to 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)));
    

    }

-1

I think the problem is that you are adding the char value to your total. This is not the same as adding the value of the digit. For example the ASCII value for 0 is 48, as you can see in the table in this wikipedia entry. One solution to your problem is to write your sum like this:

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

You can do this because you already know that the character is a digit and all digits in ASCII are in order by their value (0 is 48, 1 is 49, etc.).