#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0

    Need some help with some java code


    I got this Question for an exam due Friday any help would be appreciated. Thanks.

    Write the following methods and provide a program to test them.
    public int firstDigit(int n), returning the first digit of the argument.
    public int lastDigit(int n), returning the last digit of the argument.
    public int digits(int n), returning the number of digits of the argument.
    For example, firstDigit(1729) is 1, lastDigit(1729) is 9, and digits(1729) is 4.
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,903
    Rep Power
    1045
    Hi,

    what are your ideas? What have you tried?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0
    Was thinking something like this but not sure???

    int number = 15;
    int lastDigit = number%10;
    int firstDigit = number/10;
    System.out.println(lastDigit + firstDigit);
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,903
    Rep Power
    1045
    The last digit is correct, but the first digit only works on two digit numbers. For example, 123 / 10 will be 12.

    But you can still use this approach. You just have to repeat "cutting off" the last digit until the number has only one digit. This can be done with a loop or with recursion.

    You have to be careful with negative numbers, though.

    Another approach for this task would be to convert the integers into strings and simply use string functions to get the first character, count the length etc. But I don't think that's what you're supposed to do.

IMN logo majestic logo threadwatch logo seochat tools logo