Thread: Need some help with some java code

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. Hi,

what are your ideas? What have you tried?
3. 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);
4. 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.