-4

The code I wrote was meant to take the sum of the digits of an integer number, e.g. 143 gives out 8, 020341 give out 10.

This is the code I wrote for it

I intended for this to print out 11 but it gives me 21 instead. It works fine if the first digit isn't a 0, I'm not sure on how to make it so that it works with 0 in the first digit.

3
  • 7
    Please read: Why should I not upload images of code/data/errors?
    – Turing85
    Commented Sep 17, 2023 at 8:04
  • The literal 01235 is actually the number 669 (-> 21). 020341 is 8417 (-> 20). They are octal literals.
    – Stephen C
    Commented Sep 17, 2023 at 8:12
  • An integer with leading zero represent a number in octal not in decimal. 012345 ocal equals 5349 in decimal. And 9+4+3+5 = 21
    – zforgo
    Commented Sep 17, 2023 at 8:12

1 Answer 1

1

With the leading 0, your int is an octal.

System.out.println(012345 == 12345); // false

Not the answer you're looking for? Browse other questions tagged or ask your own question.